[英]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.