我是单元测试代码的新手,迷路了!我正在尝试为以下函数引发错误以覆盖catch块,但没有成功,我也不知道为什么。
功能:
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:');
});
});
请帮助我
答案 0 :(得分:4)
您需要先对函数进行存根,然后再解决Promise。 试试:
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:');
});