簡體   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