mocha - GradedJestRisk/js-training GitHub Wiki
List:
- test lifecycle
- beware of arrow function
Options:
- filter on test title
mocha --grep ^<NAME>
- to run test until it passes (unless MAX_FAILED_RETRIES is reached):
--retry MAX_FAILED_RETRIES
- run all tests from current directory, recursively (and list test count BTW)
--recursive .
- change timeout (default 2s)
--timeout <TIMEOUT_MILLIS>
Modifier:
- only (at any level, multiple times)
- skip
Install:
- global
npm install –g mocha
- local
npm install --save-dev mocha
"scripts": { "test": "mocha" }
Simple start
Using gitBash: mocha --colors
They can be stored in a .mocharc.js file
module.exports = { color: true, (..) }
In order to not import dev libraries in each test, you can link to a file that would contains
import chai from 'chai' import chaiAsPromised from 'chai-as-promised' import chaiExclude from 'chai-exclude' import chaiThings from 'chai-things' import sinonChai from 'sinon-chai' chai.use(chaiAsPromised) chai.use(chaiExclude) chai.use(chaiThings) chai.use(sinonChai)
Add to .eslint.json (SO)
require('dotenv').config() "standard": { "env": [ "mocha" ] }
Add to .eslint.yml
env: (..) mocha: true
If using should instead of assert: temporary solution (SO)
overrides: - files: - "*.test.js" - "*.spec.js" rules: no-unused-expressions: 'off'
Execute test several times
const _ = require('lodash'); const expect = require('chai').expect; describe('should run many times', () => { _.times(10, ()=> { it('should be true', async () => { expect(true).to.be.true; }); }); });
Execute test several times unless suceeeds (https://mochajs.org/#retry-tests)
const expect = require('chai').expect; describe('should run many times', function() { it('should be true', function() { this.retries(10); expect((new Date).getTime() % 2 === 0 ).to.be.true; }); });