Nom*_*eal 7 javascript promise typescript jestjs
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.
Run Code Online (Sandbox Code Playgroud)
我很不确定如何继续前进。来自 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();
});
});
Run Code Online (Sandbox Code Playgroud)
正在测试的代码——
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;
});
}
Run Code Online (Sandbox Code Playgroud)
我写这个答案是为了帮助其他人解决这个问题,但来源是上面 @bergi 的评论。您需要await与 一起使用expect(someFunction()).rejects.toThrowError()。这看起来像:
it(`Should throw an error when bad things happen`, async () => {
const result = doThing()
await expect(result).rejects.toThrowError(`oh no`);
});
Run Code Online (Sandbox Code Playgroud)
关于OP的后续问题:
Expect(received).rejects.toEqual() -- 收到的 Promise 被解析而不是被拒绝 -- 解析为 value: undefined
这是一个单独的问题 - 正如 Jest 所说,您期望抛出的函数是返回undefined而不是抛出错误。throw new Error('oh no')您应该在您正在调用的代码中添加类似的内容(尽管这又是一个单独的问题)。
| 归档时间: |
|
| 查看次数: |
18380 次 |
| 最近记录: |