繁体   English   中英

Mocking Jest 中的一个导入模块

[英]Mocking an imported module in Jest

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

你真的不需要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,
          });
        });
      });
    }
  );
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM