如何在 jest 中模拟动态导入模块的依赖关系

问题描述 投票:0回答:1

模块-a.js

class Math {
  pi() {
    return 3.14;
  }
}

export default Math

模块-b.js

import Math from './module-a';

const piVal = Math.pi();

export const doSomeCalc = (a) => {
  return piVal + a;
}

模块-b.test.js

describe('module b', () => {
    it('should return correct value', () => {
        // I want to mock the return value of pi() here
        return import('./module-b').then(module => {
          expect(
            module.doSomeCalc(20)
          ).toBe(23.14);
        });
    });
})

我如何在这里嘲笑

Math.pi()

我需要动态导入模块,因为一旦导入模块就会评估

Math.pi()

javascript jestjs mocking
1个回答
0
投票

首先,如果你调用

Math.pi()
方法,它应该是类的静态方法。

您可以使用

jest.doMock(moduleName, factory, options)
来模拟
module-a.js
模块

例如

module-a.js

class Math {
  static pi() {
    return 3.14;
  }
}

export default Math;

module-b.js

import Math from './module-a';

const piVal = Math.pi();

export const doSomeCalc = (a) => {
  return piVal + a;
};

module-b.test.js

describe('module b', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  it('should return correct value 1', () => {
    class MockMath {
      static pi() {
        return 1;
      }
    }
    jest.doMock('./module-a.js', () => {
      return {
        default: MockMath,
        __esModule: true,
      };
    });
    return import('./module-b').then((module) => {
      expect(module.doSomeCalc(20)).toBe(21);
    });
  });

  it('should return correct value 2', () => {
    class MockMath {
      static pi() {
        return 2;
      }
    }
    jest.doMock('./module-a.js', () => {
      return {
        default: MockMath,
        __esModule: true,
      };
    });
    return import('./module-b').then((module) => {
      expect(module.doSomeCalc(20)).toBe(22);
    });
  });
});

测试结果:

 PASS  stackoverflow/79002536/module-b.test.js
  module b
    √ should return correct value 1 (4 ms)                                                                                                                                        
    √ should return correct value 2 (1 ms)                                                                                                                                        
                                                                                                                                                                                  
Test Suites: 1 passed, 1 total                                                                                                                                                    
Tests:       2 passed, 2 total                                                                                                                                                    
Snapshots:   0 total
Time:        0.756 s, estimated 1 s
Ran all test suites related to changed files.
© www.soinside.com 2019 - 2024. All rights reserved.