Gazelover
Gazelover

Reputation: 93

how to jest mock for a custom library

abc.js

import { form } from '@myCustomLib/validator'
const _validator = new form.particulars.Validator()

function sampleFunctionIWantToTest(formInfo) {
   var error = _validator.fullValidation(formInfo)

   if(error) {return true}

   return false
}

I want to write a test for the function. I would like to mock the result for _validator.fullValidation(formInfo)

How do I mock?

Upvotes: 0

Views: 370

Answers (1)

Lin Du
Lin Du

Reputation: 102267

You can use jest.mock(moduleName, factory, options) to mock @myCustomLib/validator package.

E.g.

abc.js:

import { form } from '@myCustomLib/validator';
const _validator = new form.particulars.Validator();

function sampleFunctionIWantToTest(formInfo) {
  var error = _validator.fullValidation(formInfo);

  if (error) {
    return true;
  }

  return false;
}

export { sampleFunctionIWantToTest };

abc.test.js:

import { form } from '@myCustomLib/validator';

const validatorMock = {
  fullValidation: jest.fn(),
};

jest.mock(
  '@myCustomLib/validator',
  () => {
    const formMock = {
      particulars: {
        Validator: jest.fn(() => validatorMock),
      },
    };
    return { form: formMock };
  },
  { virtual: true },
);

describe('62949328', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should return true', () => {
    const mError = new Error('error message');
    validatorMock.fullValidation.mockReturnValueOnce(mError);
    const { sampleFunctionIWantToTest } = require('./abc');
    const actual = sampleFunctionIWantToTest();
    expect(actual).toBeTruthy();
    expect(form.particulars.Validator).toBeCalledTimes(1);
  });

  it('should return false', () => {
    validatorMock.fullValidation.mockReturnValueOnce(null);
    const { sampleFunctionIWantToTest } = require('./abc');
    const actual = sampleFunctionIWantToTest();
    expect(actual).toBeFalsy();
    expect(form.particulars.Validator).toBeCalledTimes(1);
  });
});

unit test result with 100% coverage:

 PASS  stackoverflow/62949328/abc.test.js (13.298s)
  62949328
    ✓ should return true (6ms)
    ✓ should return false (1ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 abc.js   |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        15.161s

jestjs version: "jest": "^25.5.4",

Upvotes: 1

Related Questions