[英]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.