Unit Test with jest
Tue Jan 31 2023 18:50:29 GMT+0000 (UTC)
Saved by @adelphin
npm install --save-dev jest //create file sum.js function sum(a, b) { return a + b; } module.exports = sum; //create sum.test.js const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); }); //in the package.json { "scripts": { "test": "jest" } } npm test PASS ./sum.test.js ✓ adds 1 + 2 to equal 3 (5ms) //numbers test('two plus two', () => { const value = 2 + 2; expect(value).toBeGreaterThan(3); expect(value).toBeGreaterThanOrEqual(3.5); expect(value).toBeLessThan(5); expect(value).toBeLessThanOrEqual(4.5); // toBe and toEqual are equivalent for numbers expect(value).toBe(4); expect(value).toEqual(4); }); //string test('there is no I in team', () => { expect('team').not.toMatch(/I/); }); test('but there is a "stop" in Christoph', () => { expect('Christoph').toMatch(/stop/); }); //array const shoppingList = [ 'diapers', 'kleenex', 'trash bags', 'paper towels', 'milk', ]; test('the shopping list has milk on it', () => { expect(shoppingList).toContain('milk'); expect(new Set(shoppingList)).toContain('milk'); }); //exceptions function compileAndroidCode() { throw new Error('you are using the wrong JDK!'); } test('compiling android goes as expected', () => { expect(() => compileAndroidCode()).toThrow(); expect(() => compileAndroidCode()).toThrow(Error); // You can also use a string that must be contained in the error message or a regexp expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK'); expect(() => compileAndroidCode()).toThrow(/JDK/); // Or you can match an exact error message using a regexp like below expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // Test fails expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // Test pass }); //DOM MANIPULATION npm install --save-dev jest-environment-jsdom //Emule Localstorage npm i --save-dev jest-localstorage-mock /* script in the package.json "jest": { "resetMocks": false, "setupFiles": ["jest-localstorage-mock"] } */
Comments