我想验证/断言间谍功能的结果。我正在使用带有jasmine的nestjs框架。我在一个我想“窥探”的方法上创建了一个茉莉花间谍,即窃听args和响应/异常。但是,我无法访问spied方法的返回值。
假设我有一个发射器和监听器,我想断言我的监听器在DB操作失败时抛出异常。
监听器:
onModuleInit() {
this.emitter.on('documentDeleted', d => this.onDocumentDeleted(d));
}
@CatchAndLogAnyException()
private async onDocumentDeleted(dto: DocumentDeletedEventDTO) {
this.logger.log(`Deleting document with id '${dto.id}'...`);
const result = await this.ResearchHearingTestModel.deleteOne({ _id: dto.id });
if (!result.ok) {
throw new DataAccessException(
`Deleting document with id '${dto.id}' failed. Model.deleteOne(id) result: ${result}`,
);
}
if (result.n < 1) {
throw new DocumentNotFoundException(`Deleting document with id '${dto.id}' failed.`);
}
this.logger.log(`Deleted document with id '${dto.id}.`);
}
测试:
const mockId = 123;
const spyDelete = spyOn(model, 'deleteOne').and.returnValue({ ok: 1, n: 0 });
const spyOnDeleted = spyOn(listener, 'onDocumentDeleted');
spyOnDeleted.and.callThrough();
await emitter.emit('documentDeleted', new DocumentDeletedEventDTO(mockId));
expect(spyOnDeleted).toHaveBeenCalledTimes(1);
expect(spyDelete).toHaveBeenCalledTimes(1);
expect(spyDelete).toHaveBeenCalledWith(expect.objectContaining({ _id: mockId }));
expect(spyOnDeleted).toThrow(DocumentNotFoundException);
因此,在调试时,我可以看到spyOnDeleted["[[Scopes]]"][0].spy.calls.mostRecent["[[Scopes]]"][0].calls[0].returnValue
是我可能正在寻找的承诺,但我无法访问它或验证它。
当我运行测试时,这是输出:
expect(received).toThrow(expected)
Expected name: "DocumentNotFoundException"
Received function did not throw
95 | expect(spyDelete).toHaveBeenCalledTimes(1);
96 | expect(spyDelete).toHaveBeenCalledWith(expect.objectContaining({ _id: mockId }));
> 97 | expect(spyOnDeleted).toThrow(DocumentNotFoundException);
| ^
98 | });
99 | });
100 | });
我已经看过CallThrough injected spy和其他几个类似的问题,但我仍然希望有可能通过方法监视并通过方法进行监听。有什么建议?
toThrow
不能用于间谍。您可以使用间谍来模拟行为或使用callThrough
的实际行为,然后确保使用特定参数调用该方法。但间谍不会有关于它产生的结果的信息(价值或错误),所以你不能设定它的期望。
如果你想测试onDocumentDeleted
的行为,你必须通过观察方法的影响来间接测试它。在您的情况下(使用@CatchAndLogAnyException
),它似乎写入日志!?因此,您可以监视日志并期望使用错误消息调用它。或者,您可以通过公开方法直接测试方法。