Created
June 3, 2016 06:40
-
-
Save wolframkriesing/527be3afc578d267f3a68a287feba43c to your computer and use it in GitHub Desktop.
async+await for test-readability
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This code shows two ways of writing the same test. | |
// 1) Using a promise-test-helper names hamjest, which makes testing promises simple. | |
// | |
// This uses the mocha feature that we return a promise and by that | |
// the test outcome is determined, therefore the `return` is needed. | |
// Hamjest's `promiseThat` is awesome for testing with promises, | |
// it highlights that we are inside a promise, but handles all magic, such | |
// as the reject case, etc. | |
import { | |
promiseThat, | |
isFulfilledWith, | |
} from 'hamjest'; | |
describe('Testing promises using hamjest', () => { | |
it('responds an error', () => { | |
return promiseThat(failingLoad(), isFulfilledWith({ status: 'error' })); | |
}); | |
}); | |
// 2) Using async+await instead, which allow for synchronously-code-flow. | |
// | |
// The `async` and the following `await` make this code | |
// be less indented, which highlights more the purpose of the test, | |
// the testing for the result's content. The necessary promise-wrapped | |
// test as above makes the test's purpose less prominent, it's blurred a bit | |
// inside the code required to test a promise result. | |
// This one step better in readability than `promiseThat`, but it hides | |
// complexity. | |
import 'babel-polyfill'; // for async+await | |
import { | |
assertThat, | |
equalTo, | |
} from 'hamjest'; | |
describe('Testing promises async+await', () => { | |
it('responds an error', async () => { | |
const result = await failingLoad(); | |
assertThat(result, equalTo({ status: 'error' })); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment