通过Jest了解模拟的实用程序

时间:2019-05-28 01:53:33

标签: jestjs

我完全不了解模拟的效用。看,我有下一个模块:

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

module.exports = Code;

现在,我想开玩笑地对其进行测试:

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');
  });
});

所以...这个测试会很好,但是...我的代码不是...即使我的代码错误,如果我可以设置正确的结果,那么模拟的意义何在?

1 个答案:

答案 0 :(得分:1)

应该模拟您要测试的单元。您应该嘲笑它的依赖性。

例如:

只要您在实现中有依赖项:

const dependency = require('dependency');

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

module.exports = Code;

您将能够修改其结果,从而能够测试所有方案,而无需使用依赖项的实际实现:

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');
      });
    });

});