mjackson / expect

Write better assertions
MIT License
2.29k stars 117 forks source link

Add assertions (or docs) for Promise Resolve/Reject #195

Closed alexandradeas closed 6 years ago

alexandradeas commented 7 years ago

Currently, I'm testing promises by following the pattern

it('should resolve', () => {
    return promiseThatResolves
}

it('should reject', () => {
    return promiseThatRejects.then(resolve => Promise.reject(true), reject => Promise.resolve(true));
}

Which eventually evolved into:

const expectReject = promise => promise.then(() => Promise.reject(true), () => Promise.resolve(true));
const expectResolve = promise => promise;

it('should resolve', () => expectResolve(promiseThatResolves);
it('should reject', () => expectReject(promiseThatRejects);

This can become difficult to orchestrate when the promise does more than a simple task. Is there a better way to test promises?

It'd be nice to write these as regular assertions though, such as:

expect(promiseThatRejects).toReject([Rejection, message]);
expect(promiseThatResolves).toResolve([value, message]);
ljharb commented 7 years ago

The only one that's complex is expecting rejection - for expecting resolution, just return the promise directly. mocha will do the assertion for you (your expectReject works fine).

Promises don't expose their state, so there's be no way to have a synchronous assertion for them - which is why the test framework itself is the only thing that can assert on it.