Consistently readable test descriptions for Jest
This little test description helper was inspired by Eric Elliot's RITEway and his article 5 Questions Every Unit Test Must Answer
$ npm install --save-dev jest-given # yarn add -D jest-givenconst { given, as } = require('jest-given');
const binaryStringToNumber = binString => {
if (!/^[01]+$/.test(binString)) {
throw new CustomError('Not a binary number.');
}
return parseInt(binString, 2);
};
describe('binaryStringToNumber', () => {
// Basic Test: given(what: String).it(what: String, testFunction: Function)
given('a valid binary string').it('returns the correct number', () => {
expect(binaryStringToNumber('100')).toBe(4);
});
// Nesting Tests using `as()`
given('an invalid binary string', () => {
// as(what: String).it(what: String, testFunction: Function)
as('composed of non-numbers').it('throws CustomError', () => {
expect(() => binaryStringToNumber('abc')).toThrowError(CustomError);
});
// .should() is an alias for .it()
as('with extra whitespace').should('throws CustomError', () => {
expect(() => binaryStringToNumber('abc')).toThrowError(CustomError);
});
});
});Results:
PASS
binaryStringToNumber
✓ given a valid binary string: returns the correct number
given an invalid binary string:
✓ composed of non-numbers: throws CustomError
✓ with extra whitespace: throws CustomErrorStarts a chain of descriptions that finally result in executing a test.
-
whatRequired:Stringdescribes what is given to the test function
-
nestOptional:Functionallows nesting tests under a Jestdescribe()usingwhat
If nest IS NOT provided: Returns chained function .it() (and an alias: .should())
-
Has the same signature as Jest's
it().-
whatRequired:Stringdescribes the results of the test function
-
-
When you are maintaining a large codebase, you may sometimes find a test that is temporarily broken for some reason. If you want to skip running this test, but you don't want to just delete this code, you can use
.it.skipto specify some tests to skip.
If nest IS provided, using as() for describing nested tests provides
the same API as given() however, it's description is simplified for clarity.
Add jest-given to your Jest setupTestFrameworkScriptFile configuration. See for help
"jest": {
"setupTestFrameworkScriptFile": "jest-given/setup"
}If you are already using another test framework, like jest-extended, then you should create a test setup file and require each of the frameworks you are using (including jest-given 😉)
For example:
// ./testSetup.js
require('jest-given');
require('any other test framework libraries you are using');Then in your Jest config:
"jest": {
"setupTestFrameworkScriptFile": "./testSetup.js"
}For linting you'll need to define these globals in your test files:
/* globals given, as */ISC © Buster Collings