我有一个带有一些服务的应用程序(js 类/异步方法)。服务将方法委托给其他服务。我正在尝试测试是否对每项服务进行了调用。不知何故,我对看似简单的代码进行了测试失败。
我正在尝试模拟响应,因为每个 TestService 中这些都是非常复杂的方法。
似乎一个间谍通过了,但下一个却失败了。我显然错过了一些东西。
测试服务1.ts
export class TestService1 {
static async method1(): Promise<string> {
console.log('hello world');
// complex stuff
return 'abc';
}
}
TestService2.ts
export class TestService2 {
static async method2(): Promise<string> {
console.log('hello again');
// complex stuff
return '123';
}
}
委托服务.ts
import { TestService1 } from './TestService1';
import { TestService2 } from './TestService2';
export class DelegationService {
static async delegateTasks() {
await TestService1.method1();
await TestService2.method2();
}
}
DelegationService.spec.ts
import { TestService1 } from '../TestService1';
import { TestService2 } from '../TestService2';
import { DelegationService } from '../DelegationService';
describe('DelegationService', () => {
describe('delegateTasks', () => {
it('should call delegated services', () => {
const spy1 = jest.spyOn(TestService1, 'method1').mockResolvedValue('abc');
const spy2 = jest.spyOn(TestService2, 'method2');
DelegationService.delegateTasks();
// this one passes
expect(spy1).toHaveBeenCalled();
// this one fails
expect(spy2).toHaveBeenCalled();
});
});
});
实施:
npx jest ./src/services/__tests__/DelegationService.spec.ts
结果是
spy2
失败:
好吧,我明白了。我没有
await
给DelegationService.delegateTasks();
打电话。
await DelegationService.delegateTasks();
修复了此测试。