我是单元测试代码的新手,迷路了!我正在尝试为以下函数抛出错误以覆盖 catch block ,但没有成功,我不知道为什么。
功能:
public initialize(): Promise<this> {
return Promise.resolve()
.then(() => this.getQueries())
.catch((error: Error) => {
this.connector.localLog.error(error, 'Failed to initialize Rest Poller Launcher:');
throw error;
});
}
单元测试:
it('should getQueries return error', () => {
launcher.initialize()
.then(() => {
this.getQueries = stub().throws('TypeError');
})
.catch((error: Error) => {
expect(error.message).equals('Failed to initialize Rest Poller Launcher:');
});
});
请帮帮我
最佳答案
您需要在 Promise 解析之前对函数进行 stub 。 尝试:
it('should getQueries return error', () => {
launcher.getQueries = stub().throws('TypeError');
launcher.initialize()
.then(() => {
// this should not happen
})
.catch((error: Error) => {
expect(error.message).equals('Failed to initialize Rest Poller Launcher:');
});
关于javascript - 尝试在 then 中测试我的 catch block 没有成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55578973/