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