【问题标题】:How can I Inject a Service into my test when my service has an injectable in its constructor?当我的服务在其构造函数中有可注入对象时,如何将服务注入我的测试?
【发布时间】:2018-01-10 02:56:53
【问题描述】:

我想为我的 DataService 类创建一个测试脚本。我知道我需要将服务注入到类中,但 DataService 构造函数需要 Apollo 可注入。我发现了几个无效的过时解决方案。任何帮助将不胜感激!

@Injectable()
export class DataService {

    constructor(private apollo: Apollo) {}

    ...

}

这是我需要 DataService 的测试:

const chai = require('chai');
const should = chai.should();
const req = require("request-promise");
import {inject} from  "@angular/core/testing";
import { DataService } from '../data.service'

describe('User', () => {


    beforeEach(() => {

    })

    it('Can be created.', (done) => {

    });
})

【问题讨论】:

    标签: javascript angular typescript dependency-injection apollo


    【解决方案1】:

    您将需要创建一个包含提供程序列表的 TestModule,这些提供程序本质上是 Angular2 遵循的规则,以便在请求某些内容时注入 什么

    beforeEach(() => {
    
      TestBed.configureTestingModule({
        providers: [Apollo] // This will return an instance of the actual Apollo class (you will need to import Apollo in your spec file)
      }).compileComponents();
    
    });
    

    这将允许您在正在测试的代码中注入 Apollo 服务。但是,您可能不想注入实际的 Apollo 服务,在这种情况下,您可以创建一个模拟 apollo 类,并告诉测试组件注入该假类来代替 Apollo

    class MyMockApollo {...} // should mock up any methods that your tests will rely on
    
    beforeEach(() => {
    
      TestBed.configureTestingModule({
        providers: [
          {provide: Apollo, useClass: MyMockApollo} // This will return an instance of MyMockApollo
        ]
      }).compileComponents();
    
    });
    

    第三种选择是提供一个而不是一个

     providers: [
          {provide: Apollo, useValue: mockApolloInstance} // This will return the exact thing you give it
        ]
    

    【讨论】:

    • 谢谢 jason,我刚刚尝试过,但出现错误:“var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec']; ^ ReferenceError: Zone is not defined”
    • 我发现 mocha/chai 和 angular 相处得不太好。我正在切换到推荐的工具 Karma/Jasmine。感谢您的帮助
    猜你喜欢
    • 2021-06-20
    • 2023-03-28
    • 2019-04-25
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多