我正在使用 Typescript 为我的 Angular 项目编写单元测试
当我尝试为某些服务创建模拟时,我使用这种方式:
const serviceMock = <IMyService>{
method: _.noop,
};
beforeEach(inject($injector => {
testingService = new AccountingService(serviceMock);
spyOn(serviceMock, 'method').and.callFake(()=>'hello');
}
这工作正常
但是当我尝试使用 jasmine.createSpy()
时,出现编译错误:
const serviceMock = <IMyService>{
method: jasmine.createSpy('method').and.callFake(()=>'hello'),
};
Type '{ method: Spy;}' cannot be converted to type 'MyService'. Property 'getParams' is missing in type '{ method: Spy;}'.
但是getParams
是MyService
的私有(private)方法
我做错了什么?
最佳答案
使用 Jasmine 已经定义和使用的类型 SpyObj<T>
.
const serviceMock: jasmine.SpyObj<IMyService> = jasmine.createSpyObj<IMyService>('service',['method']);
这样,IMyService 的每个方法都将使用 Spy 方法进行扩充:
serviceMock.method.and.callFake(()=>'hello');
关于angular - typescript + jasmine.createSpy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44670443/