Overview
Jest offers the function expect() in combination with the properties resolves or rejects to test a function that return a Promise. This is just a reminder.Link: An Async Example
describe('Testing promise with jest', () => {
const buildAsyncFunction = function(promiseMustSucceed, result) {
return (url) =>
new Promise((resolve, reject) => {
if(promiseMustSucceed)
resolve(result);
else
reject(result);
});
};
const errorResult = "error";
const okResult = "ok";
const testUrl = "http://foo";
it('Async function should succeed', () => {
const f = buildAsyncFunction(true, okResult);
expect( f(testUrl) ).resolves.toEqual(okResult);
});
it('`Async function should failed', () => {
const f = buildAsyncFunction(false, errorResult);
expect( f(testUrl) ).rejects.toEqual(errorResult);
});
it('Async function should failed, but promise returned by catch() should succeed', () => {
const func0 = buildAsyncFunction(false, errorResult);
const promise0 = func0(testUrl);
expect( promise0 ).rejects.toEqual(errorResult);
const ff = promise0
.then(() => { throw Error('then() block unexpectedly called')})
.catch((error) => {
console.log(`function f() failed error:${error}`);
expect(error).toEqual(errorResult);
return okResult;
});
expect(ff).resolves.toEqual(okResult);
});
});
No comments:
Post a Comment