Jest
From Logic Wiki
Jest is used by Facebook to test all JavaScript code including React applications.
Contents
Installation
npm i jest --save-dev
in package.json under "scripts" section
"scripts":{
"test":"jest"
}
Create a folder named "tests", create a file named sample.test.js and write a sample test like this
test('Our first test', () => {
});
run the sample test form the command prompt
npm test
Usage
a simple test file
const lib = require('../lib');
test('absolute - should return a positive number if input is positive', () => {
const result = lib.absolute(1);
expect(result).toBe(1);
});
Grouping
const lib = require('../lib');
describe('GroupName', ()=>{
it('should return this if that is entered', () => {
const result= lib.absolute(1);
expect(result).toBe(1);
});
it('should return other if something else is entered', () => {
const result= lib.absolute(2);
expect(result).toBe(2);
});
});
Testing Exceptions
const lib = require('../lib');
describe('GroupName', ()=>{
it('should throw if username is falsy', () => {
// null, undefined, NaN, '', 0, false
expect(() => {lib.registerUser(null)}.toThrow();
});
});
Continually Running Tests
in package.json under "scripts" section we add watchAll flag
"scripts":{
"test":"jest --watchAll"
}
Jest Mock Function
const mockFunction = jest.fn(); // mockFunction.mockReturnValue(1); // mockFunction.mockResolvedValue(1); mockFunction.mockRejectedValue(1); const result = await mockFunction();
db.getCustomerSync = jest.fn().mockReturnValue({ email:'a' });
mail.send = jest.fn(); expect(mail.send).toHaveBeenCalled();
for the arguements
expect(mail.send.mock.calls[0][0]).toBe('a'); //first arguement
expect(mail.send.mock.calls[0][1]).toMatch(/order/); //second arguement