在测试中使用jasmine的spy功能来确保模拟服务函数被调用。
示例代码:
在测试文件中,我们可以使用TestBed来注入我们要测试的服务类,并创建一个spy函数来监视该服务的函数调用情况:
import { TestBed } from '@angular/core/testing';
import { SomeService } from './some.service';
describe('SomeComponent', () => {
let someServiceSpy: jasmine.SpyObj;
beforeEach(() => {
someServiceSpy = jasmine.createSpyObj('SomeService', ['someFunction']);
TestBed.configureTestingModule({
providers: [
{ provide: SomeService, useValue: someServiceSpy }
]
});
});
it('should call someFunction', () => {
const fixture = TestBed.createComponent(SomeComponent);
// perform some actions that trigger the function call
expect(someServiceSpy.someFunction).toHaveBeenCalled();
});
});
在上述示例中,我们首先创建了一个模拟的SomeService实例,并注入到TestBed中。然后,在测试函数中,我们使用这个实例的spy函数来监视‘someFunction’是否被调用。最后,我们使用jasmine的‘toHaveBeenCalled()’函数来断言该函数确实被调用了。