在Jest中模拟导入的模块

时间:2020-06-04 15:56:54

标签: javascript module mocking jestjs

我试图弄清楚如何在测试文件中用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,
}));

1 个答案:

答案 0 :(得分: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,
          });
        });
      });
    }
  );
});