我有一组类以这种方式在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),但是我是找不到如何嘲笑他们。有办法吗?
答案 0 :(得分:1)
这两个构造函数的名称分别为各自模块的出口。
您可以在模块工厂中使用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 });
// ...
})