我想为我的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) => {
});
})
答案 0 :(得分:0)
您将需要创建一个包含提供程序列表的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
]