Mocha out of the box often requires a lot of setup and teardown code in beforeEach/afterEach filters. Using this library, you can get rid of those entirely and build your tests declaratively by chaining functionality together. Using the builtin plugins and your own, you create bits of functionality and chain them together with a concise syntax. It will greatly reduce the amount of repetition in your codebase.
It might be compatible with other testing libraries as well (e.g. jest), but would require a couple small changes. Let me know if you'd be interested in this.
As an example, here is what a test file might look like for an application setup with fancy-mocha. This chain could partially be stored to a variable for reuse.
describe('api',()=>{
fancy()
// [custom plugin] initializes the db
.initDB({withUser: mockDBUser})
// [custom plugin] uses nock to mock out github API
.mockGithubAPI({user: mockGithubUser})
// [custom plugin] that calls the API of the app
.call('POST','/api/user/foo',{id:mockDBUser.id})
// add adds to the context object
// fetch the newly created data from the API (can return a promise)
catch errors in a declarative way. By default, ensures they are actually thrown as well.
describe('catch tests',()=>{
fancy()
.run(()=>{thrownewError('foobar')})
.catch(/foo/)
.end('uses regex')
fancy()
.run(()=>{thrownewError('foobar')})
.catch('foobar')
.end('uses string')
fancy()
.run(()=>{thrownewError('foobar')})
.catch(err=>expect(err.message).to.match(/foo/))
.end('uses function')
fancy()
// this would normally raise because there is no error being thrown
.catch('foobar',{raiseIfNotThrown:false})
.end('do not error if not thrown')
})
Without fancy, you could check an error like this:
it('dont do this',()=>{
try{
myfunc()
}catch(err){
expect(err.message).to.match(/my custom errorr/)
}
})
But this has a common flaw, if the test does not error, the test will still pass. Chai and other assertion libraries have helpers for this, but they still end up with somewhat messy code.
Nock
Uses nock to mock out HTTP calls to external APIs. You'll need to also install nock in your devDependencies.
Automatically calls done() to ensure the calls were made and cleanAll() to remove any pending requests.
This is used for tests that ensure that certain stdout/stderr messages are made.
By default this also trims the output from the screen.
You can use the library stdout-stderr directly for doing this, but you have to be careful to always reset it after the tests run. We do that work for you so you don't have to worry about mocha's output being hidden.