Jest

Updated 12/01/2024

Jest is a javaScript testing framework.

Pre Cursor

  • Install Node so we can run the JS locally https://nodejs.org/en/download, check its installed with node -v
  • npm init, name jesttesting and enter defaults, for test type jest
  • this creates package.json
  • npm install --save-dev jest to install jest
  • create our root module index.js and test for it index.test.js

The package.json file should look like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "jesttesting",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.7.0"
}
}

  • Then to create a js file that the browser can use run npm install -g webpack webpack-cli
  • create webpack.config.js (it had to have the absolute path)
1
2
3
4
5
6
7
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
path: 'C:\\dev\\jest\\dist'
}
};
  • Run webpack, this creates the bundle in dist which should be browser friendly.

Life Cycle

Note that it and test are the same thing and you nest a describe in a describe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
describe('unit of work should', () => {
beforeAll(() => {
//setup spyOn
});
it(`do x under y predicate "${allowsVariableInName}"`, () => {
//arrange, act, expect
});
it('do foo under baz predicate', () => {
//arrange, act, expect
});
afterAll(() => {
//mockRestore
});
});

Update index.js

This is a simple example that redirects a user to a new version of the page when the js file is loaded in the master (so avalible on all pages)

Data driven

1
2
3
4
5
6
describe('unit of work', () => {
[
{ abName: true, expected: true },
{ abName: false, expected: false }
].forEach(({ abName, expected }) =>
it(`should ${expected ? '' : 'not'} use 'child-component-to-maybe-show' if abName feature is ${abName}`, () => {

TBA

1
2
3
4
5
6
7
8
9
expect(spy).toHaveBeenCalledTimes(1);

toHaveBeenCalledWith

toBeInstanceOf

toBe

toMatchSnapshot

References