在我的一个单元测试文件中,我需要使用不同的模拟来多次模拟相同的服务。
import { MyService } from '../services/myservice.service';
import { MockMyService1 } from '../mocks/mockmyservice1';
import { MockMyService2 } from '../mocks/mockmyservice2';
describe('MyComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
providers: [
{ provide: MyService, useClass: MockMyService1 }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MapComponent);
mapComponent = fixture.componentInstance;
fixture.detectChanges();
});
describe('MyFirstTest', () => {
it('should test with my first mock', () => {
/**
* Test with my first mock
*/
});
});
describe('MySecondTest', () => {
// Here I would like to change { provide: MyService, useClass: MockMyService1 } to { provide: MyService, useClass: MockMyService2 }
it('should test with my second mock', () => {
/**
* Test with my second mock
*/
});
});
});
我发现函数overrideProvider存在,但我没有在我的测试中成功使用它。当我在一个“it”中使用它时,提供者不会改变。我没有找到一个调用此函数的示例。你能解释一下如何正确使用它吗?或者你有其他方法吗?
{useValue: new MockRequestService1()}
对我来说是缺失的一部分。可惜它不像TestBed.configureTestingModule()
一样接受useClass
。 - Jacob Stamm