Javascript - Jest Test Runner
Table of Contents
1 - About
Jest is a test runner from Facebook for client-side JavaScript applications and React applications specifically.
Jest ships with jsdom for DOM manipulation testing.
2 - Articles Related
3 - Installation
3.1 - Idea
4 - Usage
4.1 - Object
let oneObj = {name: 'nico', id: 2};
expect(oneObj).toEqual({name: 'nico'}) // false, should be exactly equal all Obj keys and values
expect(oneObj).toMatchObject({name: 'nico'}) // true
4.2 - Mock
4.3 - Assertion
The assertion library is jasmine
Example:
test('Crawler Base Url Test', async () => {
const fn = () => Crawler.setUrl("test");
expect(fn).toThrow(SyntaxError);
})
5 - File Structure
Jest will look for test files with any of the following popular naming conventions:
- Files with .js suffix in __tests__ folders.
- Files with .test.js suffix.
- Files with .spec.js suffix.
The .test.js / .spec.js files (or the __tests__ folders) can be located at any depth under the src top level folder.
It's recommended to collocate the test file with the source file (ie put the test files (or __tests__ folders) next to the code they are testing ) because of:
- shorter relative imports (ie Source)
- searching the test is easier
6 - Run
6.1 - Node
test is a global variable injected by Jest. You need to run your tests through jest
- Test
test('3 equal 3', () => {
expect(3).toBe(3);
});
- Run
jest my-test --notify --config=config.json
6.2 - Browser
- https://github.com/kvendrik/jest-lite
<script src="https://unpkg.com/[email protected]/dist/core.js"></script>
expect = jestLite.core.expect;
try {
expect(3).toBe(2)
} catch (e) {
// If the test is not good an exception is fired.
console.log(e.message);
}