I am facing a difficult error message from Jest that I can't seem to figure out. The error message indicates that the promise is being resolved instead of rejected, causing an unhandled promise rejection. It's confusing because Jest expects an error to be thrown, but when it is thrown, it claims it is unhandled. I feel like I must be missing something here.
Below is the error message I am receiving:
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.
Here is the code snippet that is causing the error:
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();
});
});
And here is the relevant code being tested:
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;
});
}