[英]Mocking constructor of a class with jasmine, jest or ts-mockito
我有一組類以這種方式接收 angular 之外的一些依賴項。
import {TypeATest} from '...../TypeA.model'
import { TypeBTest } from '..../TypeB.model'
import { SomeDependency } from './services/SomeDependency'
import { SomeAnother } from './services/SomeAnother'
// ....
@Injectable({
providedIn: 'root'
})
export class TestingService {
this.activeTest: AnyTestType;
constructor(private readonly injectorService: InjectorService) {}
loadTest(TypeOfTest) {
const someDependency = this.injectorService.get(SomeDependency)
const someAnother = this.injectorService.get(SomeAnother)
switch(TypeOfTest) {
case TypeA:
injector
this.activeTest = new TypeATest(someDependency, someAnother);
break;
case TypeB:
this.activeTest = new TypeBTest(someAnother);
break;
}
}
startTest(){
this.activeTest.start()
}
// .. more this.activeTest uses...
}
我正在對加載該外部類的服務進行單元測試,但我不想創建TypeATest
、 TypeBTest
或類似的服務,而只是模擬結果(它們都具有相同的 API),但我無法找到如何模擬它們。 有沒有辦法做到這一點?
這兩個構造函數被命名為它們各自模塊的導出。
您可以使用帶有模塊工廠的jest.mock
模擬整個模塊:
jest.mock('...../TypeA.model', () => {
const start = jest.fn();
const result = { start };
return jest.fn(() => result);
});
test('something', () => {
// ...
});
...或僅使用jest.spyOn
模擬模塊的命名導出:
import * as TypeB from '..../TypeB.model';
test('something', () => {
const spy = jest.spyOn(TypeB, 'TypeBTest');
const start = jest.fn();
spy.mockReturnValue({ start });
// ...
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.