Karma is used as a test runner and Webpack is used to instrument and bundle test code.
By default, tests are written in *-test.js
files in the tests/
directory.
Mocha is configured as the default test framework and expect is made available by default for assertions and spies without having to install it in your own devDependencies
.
Don't worry if none of the above is to your taste, as Karma can be configured using the nwb config file.
This is an example of a minimal unit test which will run with nwb test
straight out of the box:
import expect from 'expect'
describe('Minimal unit test', () => {
it('informs the reader', () => {
expect('tautology').toEqual('tautology')
})
})
Default test Webpack config is configured to alias 'src'
to the src/
directory, allowing you to perform top-level imports for the code to be tested, instead of having to use '../'
paths to climb out of the tests/
dir.
This allows you to organise your code under tests/
whichever way you want without having to adjust how you import the code to be tested.
For example, if the following directory structure exists in your project:
src/
components/
Finagler.js
Then your tests can import this component like so:
import Finagler from 'src/components/Finagler'
If you need to run some code before any of your tests run, the recommended way is to create a context module for Webpack to load and use karma.tests
config to point to it. You will need to use use require.context()
in this module to specify which test files to run.
For example, if you need to configure an assertion library before running any tests and your tests are in .spec.js
files under src/
, you could create the following tests.webpack.js
module in the root of your project...
var chai = require('chai')
var chaiEnzyme = require('chai-enzyme')
chai.use(chaiEnzyme())
var context = require.context('./src', true, /\.spec\.js$/)
context.keys().forEach(context)
...then point to it in nwb.config.js
:
module.exports = {
karma: {
tests: 'tests.webpack.js'
plugins: [
require('karma-chai')
],
frameworks: ['mocha', 'chai']
}
}
A context module is also commonly used to load polyfills, but you don't need to worry about that - nwb handles injecting Babel's polyfills into Karma tests for you.
Passing a --coverage
flag when running tests will generate a code coverage report in coverage/
.
Coverage will be measured automatically when your tests are run on Travis CI, or any other environment where a CONTINUOUS_INTEGRATION
environment variable is set to true
.
All project templates come with a .travis.yml
which will post coverage results to codecov.io and coveralls after a successful build.