我有以下扩展 nestjs Logger 的服务。
@Injectable({scope:Scope.TRANSIENT})
export class LogService extends Logger {
async log(message: string, context?: string): Promise<void> {
super.log(message, context);
super.log(message, context);
super.log(message, context);
super.log(message, context);
super.log(message, context);
}
async debug(message: string, context?: string): Promise<void> {
super.debug(message, context);
super.debug(message, context);
super.debug(message, context);
super.debug(message, context);
super.debug(message, context);
}
我有一个测试类如下:
describe('LogService', () => {
let service: Logger;
const inputMessage = 'message';
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [LogService],
}).compile();
service = await module.resolve<LogService>(LogService);
});
afterEach(() => {
jest.clearAllMocks();
});
// test 1
it('should call Logger\'s log method', async () => {
const loggerSpy = jest.spyOn(Logger.prototype, 'log');
await service.log(inputMessage);
expect(loggerSpy).toHaveBeenCalledTimes(5)
});
// test2
it('should call Logger\'s debug method', async () => {
const loggerSpy = jest.spyOn(Logger, 'debug');
await service.log(inputMessage);
expect(loggerSpy).toHaveBeenCalledTimes(5)
});
这 2 个测试将如上所示通过,但请注意这 2 个测试的 jest.spyOn(Logger...) 行,它们是不同的。
当我修改 jest spy 台词时,我遇到以下问题:
对于第二次测试,我尝试将线路切换到 jest.spyOn(Logger.prototype, 'debug'),现在预期的调用次数为 10
对于第一次测试,我尝试将线路切换到 jest.spyOn(Logger, 'log'),现在预期的调用次数为 0。
是什么导致了两次测试之间的这种不一致?