简体   繁体   中英

Mocking an imported module in Jest

I'm trying to figure out how to mock a constant ( DEFAuLT_OPTIONS ) with Jest in my test file

I have the following file structure:

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

Files

// 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);

  });
});

How can I -

  • Mock the value of DEFAULT_OPTIONS for a single test?
  • Mock the value of DEFAULT_OPTIONS for a suite of tests? (If different)

Thanks!

EDIT: I tried the following but the module seems to have a value of undefined

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

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

You don't really need jest.mock as it's just a constant.

You can:

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

and this is how you can modify it for a suit of tests

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,
          });
        });
      });
    }
  );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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