我是测试领域的新手,如果这个问题太明显了,请抱歉!
我有一个功能齐全且复杂的angular 9项目。我将在这里简单地解释我的问题:
我有多项服务:
现在我已经通过创建间谍等成功地测试了Service_MAIN。
let service: Service_MAIN;
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'put', 'post', 'delete', 'patch']);
routerSpy = jasmine.createSpyObj('Router', ['navigate']);
TestBed.configureTestingModule({
imports: [MatSnackBarModule],
providers: [
Service_MAIN,
{provide: HttpClient, useValue: httpClientSpy},
{provide: Router, useValue: routerSpy},
SnackBarService
]
});
service= TestBed.inject(Service_MAIN);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
...
...
现在,当我想测试Service_A和Service_B时,是否需要再次为我的Service_MAIN创建一个间谍并传递httpClientspy,routerSpy等?
此外,如果我曾经为Service_MAIN创建一个间谍以测试Service_A,是否还需要为Service_B创建相同的间谍?
这会在我的测试文件中产生很多重复。
注意:Service_A不直接使用HTTPCLIENT,而是使用Service_MAIN间接进行HTTP调用。
答案 0 :(得分:0)
在测试Service_A
或Service_B
时,您可以为spyObj
创建一个Service_MAIN
并模拟Service_A
或{{1} }。
测试Service_B
的示例。
Service_A
对于路由器,您还应该导入let service: Service_A;
let mockServiceMain: any
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('serviceMain', [/* Put the public methods of serviceMain here as comma separated strings*/]);
TestBed.configureTestingModule({
imports: [],
providers: [
// Inject the actual service because it is to be tested
Service_A,
// when the service requests for Service_MAIN, use the mock value
{ provide: Service_MAIN, useValue: mockServiceMain },
// your other providers or mock providers can go here
]
});
service = TestBed.inject(Service_A);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
而不是对它进行存根(https://angular.io/api/router/testing/RouterTestingModule)。对于HTTP同样适用,您应该使用HttpTestingController(https://angular.io/api/common/http/testing/HttpTestingController)。