【问题标题】:Mocking an imported module in Jest在 Jest 中模拟导入的模块
【发布时间】:2020-06-05 22:40:44
【问题描述】:

我试图弄清楚如何在我的测试文件中使用 Jest 模拟一个常量 (DEFAuLT_OPTIONS)

我的文件结构如下:

src/
  Builder/
    - Constants.js
    - Builder.js
    - Builder.test.js

文件

// Constants.js
// Define a set of defaults to be used in my production build

const DEFAULT_OPTIONS = {
  enableTransparency: true,
  threshold: 100
};

export {
  DEFAULT_OPTIONS
}

// Builder.js
// Exports a `buildTree` function, which uses the constants

import { DEFAULT_OPTIONS } from './Constants';

function buildTree(options) {
  return {
    root: '/',
    options: { ...options, ...DEFAULT_OPTIONS }
  };
}

export { buildTree };

// Builder.test.js

import { DEFAULT_OPTIONS } from './Constants';
import { buildTree } from './Builder';

describe('Builder', () => {
  it('some description', () => {

    // How to mock value of `DEFAULT_OPTIONS` here so that
    // the call to `buildGTree` uses my mocked version? 

    const options = { foo: 'bar' };
    const result = buildTree(options);

  });
});

我怎么能 -

  • 为单个测试模拟DEFAULT_OPTIONS 的值?
  • 为一组测试模拟DEFAULT_OPTIONS 的值? (如果不同)

谢谢!

编辑:我尝试了以下方法,但该模块的值似乎为 undefined

const mockDefaultOptions = {
  optionA: 'a',
  optionB: 'b'
}

jest.mock('./Constants', () => ({
  DEFAULT_OPTIONS: mockDefaultOptions,
}));

【问题讨论】:

    标签: javascript module mocking jestjs


    【解决方案1】:

    您实际上并不需要jest.mock,因为它只是一个常数。

    你可以:

    // import constants
    import Constants from './Constants'
    // modify DEFAULT_OPTIONS' value
    Constants.DEFAULT_OPTIONS = {
      threshold: 444
    }
    // then invoke your function
    const result = buildTree(options);
    

    这就是您可以修改它以进行一系列测试的方法

    import { buildTree } from "./Builder";
    
    describe("Builder", () => {
      describe.each([333, 444, 555])(
        "with DEFAULT_OPTIONS.threshhold = %d",
        (threshold) => {
          describe("buildTree", () => {
            const Constants = require("./Constants");
            const options = { foo: "bar" };
            let result;
            beforeAll(() => {
              Constants.DEFAULT_OPTIONS = {
                threshold,
              };
              result = buildTree(options);
            });
    
            it("some description", () => {
              expect(result).toHaveProperty("options", {
                ...options,
                threshold,
              });
            });
          });
        }
      );
    });
    
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2023-03-11
      • 2019-04-01
      • 2019-03-05
      • 2021-01-21
      • 2017-02-06
      • 1970-01-01
      相关资源
      最近更新 更多