An example code from coddee. These are a set of tests written using mocha and chai.
In webhook_method_tests.js
, I am testing that the method saves a MongoDB document into a collection.
In webhook_tests.js
, I am testing that this method is called when a webhook comes in from GitHub.
I wrote two different tests because the middleware that detects the GitHub webhook is an event emitter,
and I don't have much control over how long it takes to actually save a document to a collection.
The fact that I am testing an asynchronous middleware means that I have to use setTimeout
to make my assertion. Also, write operations are not always cheap, and
I have to delay my assertion for quite a bit (~800ms), which is unacceptable if you have a large test suite.
In spite of the significantly delayed assertion, the test would be still brittle because sometimes DB operation might take longer than my delay.
I addressed the problem of delayed assertion by separating the tests: one for testing that the correct method is called, and another for testing that the method saves the data in the db. In the first one, I still need to use setTimeout
, but the delay is only 50ms
, and the test is very solid.