Jest mock module multiple times with different values

前端 未结 2 1699
小鲜肉
小鲜肉 2021-01-05 09:14

I have a function that I want to test and this function uses an imported module:

var a = require(\'./a\');

function add(b) {
  return a + b;
}

module.expor         


        
相关标签:
2条回答
  • 2021-01-05 09:54

    Add

    beforeEach(() => {
        jest.resetModules();
    });
    

    Final tests

    describe('add', () => {
    
        beforeEach(() => {
            jest.resetModules();
        });
    
        it('should add the mock number 5 to 2', () => {
            jest.setMock('./a', 5);
            const add = require('./add');
            expect(add(2)).toBe(7);
        });
    
        it('should add the mock number 2 to 2', () => {
            jest.setMock('./a', 2);
            const add = require('./add');
            expect(add(2)).toBe(4);
        });
    });
    

    Demo: https://repl.it/repls/TrustingBelatedProprietarysoftware

    0 讨论(0)
  • 2021-01-05 10:01

    To add to @Gigi's solution, I created another example, using jest.mock:

    In the file multiplier.ts, multiplier is the exported function we want to test:

      // file: multiplier.ts
    
      import {getNumber} from './get-number'
      const multiplier = (num:number) => num * getNumber()
      export {multiplier}
    

    In the file get-number.ts, getNumber is the module we want to mock:

      // file: get-number.ts
    
      const getNumber = () => 2
      export {getNumber}
    

    Here is the test:

      // file: multiplier.test.ts
    
      // import { multiplier } from "./multiplier"  // <-- this will not work
      
      describe("[multiplier]", () => {
        beforeEach(() => {
          jest.resetModules()
        })
      
        it('should mock getNumber so that getNumber return 3', () => {
          const mockReturn = 3
      
          jest.mock( './get-number', () => (
            { getNumber: jest.fn(()=>mockReturn) }
          ))
      
          const { multiplier } = require('./multiplier')
          expect(multiplier(2)).toBe(6)
        })
      
        it('should mock getNumber so that getNumber return 4', () => {
          const mockReturn = 4
      
          jest.mock( './get-number', () => (
            { getNumber: jest.fn(()=>mockReturn) }
          ))
      
          const { multiplier } = require('./multiplier')
          expect(multiplier(2)).toBe(8)
        })
      
        it('should mock getNumber so that getNumber return 5', () => {
          const mockReturn = 5
      
          jest.mock( './get-number', () => (
            { getNumber: jest.fn(()=>mockReturn) }
          ))
      
          const { multiplier } = require('./multiplier')
          expect(multiplier(2)).toBe(10)
        })
      })
    

    Note: for this to work, we need to use require to import multiplier.ts

    0 讨论(0)
提交回复
热议问题