enbermudas
enbermudas

Reputation: 1615

Understand the utility of mocks with Jest

I can't understand at all the utility of mockings. See, I have the next module:

function Code() {
  this.generate = () => {
    const result = 'code124';
    return result;
  };
}

module.exports = Code;

Now, I want to test it with jest:

const Code = require('../lib/code');

jest.mock('../lib/code', () => {
  return jest.fn().mockImplementation(() => {
    return {
      generate: () => [1, 2, 3]
    };
  });
});

describe('Code', () => {
  test('returns the code "code123"', () => {
    const code = new Code();
    expect(code.generate()).toBe('code123');
  });
});

So... This test will be fine but... My code ain't so... what's the point about mocking if I can set a correct result even though my code is wrong?

Upvotes: 0

Views: 27

Answers (1)

Teneff
Teneff

Reputation: 32158

You're NOT supposed to mock the unit you're testing. You're supposed to mock it's dependencies.

for example:

whenever you have a dependency in the implementation:

const dependency = require('dependency');

function Code() {
  this.generate = () => {
    const result = 'code' + dependency.getNumber();
    return result;
  };
}

module.exports = Code;

you'll be able to modify it's results to be able to test all scenarios without using the actual implementation of your dependency:

const dependency = require('dependency');
const Code = require('../lib/code');
jest.mock('dependency');

describe('Code', () => {

    describe('when dependency returns 123', () => {
      beforeAll(() => {
        dependency.getNumber.mockReturnValue('123');
      });

      it('should generate code123', () => {
        const code = new Code();
        expect(code.generate()).toEqual('code123');
      });
    });

    describe('when dependency returns 124', () => {
      beforeAll(() => {
        dependency.getNumber.mockReturnValue('124');
      });

      it('should generate code123', () => {
        const code = new Code();
        expect(code.generate()).toEqual('code124');
      });
    });

});

Upvotes: 1

Related Questions