繁体   English   中英

Jest - UnhandledPromiseRejection - Received promise resolved 而不是 rejected

[英]Jest - UnhandledPromiseRejection - Received promise resolved instead of rejected

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 而不是 rejected -- Resolved to value: undefined

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM