writing unit tests with jest code example

Example 1: jest

beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
  beforeAll(() => console.log('2 - beforeAll'));
  afterAll(() => console.log('2 - afterAll'));
  beforeEach(() => console.log('2 - beforeEach'));
  afterEach(() => console.log('2 - afterEach'));
  test('', () => console.log('2 - test'));
});

// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
Copy

Example 2: different types of unit testing in jest

describe('in the math global object', () => {
 
  describe('the random function', () => {
    it('should return a number', () => {
      expect(typeof Math.random()).toEqual('number');
    })
    it('should return a number between 0 and 1', () => {
      const randomNumber = Math.random();
      expect(randomNumber).toBeGreaterThanOrEqual(0);
      expect(randomNumber).toBeLessThan(1);
    })
  });
 
  describe('the round function', () => {
    it('should return a rounded value of 4.5 being 5', () => {
      expect(Math.round(4.5)).toBe(5);
    })
  });
 
})

Example 3: jest

Jest is a JavaScript testing framework maintained by Facebook, Inc. with a
focus on simplicity.

It works with projects using: Babel, TypeScript, Node.js, React, Angular and
Vue.js.

It aims to work out of the box and config free.