gpt4 book ai didi

javascript - Jest - UnhandledPromiseRejection - 收到的 promise 已解决而不是被拒绝

转载 作者:行者123 更新时间:2023-12-05 00:29:28 30 4
gpt4 key购买 nike

Jest 向我抛出以下错误消息——

node:internal/process/promises:245
triggerUncaughtException(err, true /* fromPromise */);
^

[UnhandledPromiseRejection: This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled with .catch().
The promise rejected with the reason "Error: expect(received).rejects.toThrowError()

Received promise resolved instead of rejected
Resolved to value: undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
error Command failed with exit code 1.
我很不确定如何继续前进。来自 Jest 的错误消息读起来像是失败了,因为 promise 解决了并且它期望抛出一个错误......但是当抛出一个错误并说它未处理时感到不安?我一定完全理解错了。
这是我的测试——
    describe('credentials test', () => {
it('without credentials', async () => {
const provider = new Provider();
provider.configure(testConfig);
const spyon = jest.spyOn(Credentials, 'get').mockImplementation(() => {
return Promise.reject('err');
});

const action = async () => {
await provider.create({
param: val,
});
};

expect(action()).rejects.toThrowError();
spyon.mockRestore();
});
});
以及正在测试的代码——
    public async create(
params: CreateInput
): Promise<CreateOutput> {
const cmd = new Command(params);
const client = this._init();

try {
const credentialsOK = await this._ensureCredentials();
if (!credentialsOK) {
logger.error(NO_CREDS_ERROR_STRING);
throw Error;
}

const output = await client.send(cmd);
return output;
} catch (error) {
logger.error(`error - ${error}`);
}
}

private async _ensureCredentials() {
return await Credentials.get()
.then(credentials => {
if (!credentials) return false;
const cred = Credentials.shear(credentials);
logger.debug('set credentials', cred);
this._config.credentials = cred;

return true;
})
.catch(error => {
logger.warn('ensure credentials error', error);
return false;
});
}

最佳答案

我写这个答案是为了帮助其他人解决这个问题,但来源是上面@bergi 的评论。您需要使用 awaitexpect(action()).rejects.toThrowError() .这看起来像:

  it(`Should throw an error when bad things happen`, async () => {
const result = doThing()
await expect(result).rejects.toThrowError(`oh no`);
});
关于OP的后续问题:

expect(received).rejects.toEqual() -- Received promise resolved instead of rejected -- Resolved to value: undefined


这是一个单独的问题 - 正如 Jest 所说,您期望抛出的函数正在返回 undefined而不是抛出错误。您应该添加类似 throw new Error('oh no') 的内容到您正在调用的代码(尽管这又是一个单独的问题)。

关于javascript - Jest - UnhandledPromiseRejection - 收到的 promise 已解决而不是被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67711112/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com