模拟用于笑话测试的全局可用对象



我正在尝试测试一个使用自定义窗口属性引用的js模块。基本上,在另一个文件中我有:

const component = window.externalFunctions.component;

我正在测试的js模块使用这个component没有任何类型的导入,并通过在文档中创建一个<script>动态加载在应用程序中。里面有一个示例函数:

const getDate = (date) => {
let currentTime = date;
currentTime.setTime(currentTime.getTime() + component.clientTimeZoneShiftInMinutes*60*1000);
return currentTime;
}
export const getShift = (date) => {
const currentDate = getDate(date);
.....
}

当我运行一个简单的jest测试用例,它说:ReferenceError: component is not defined模块内部。在我的helpers.test.js中我有:

beforeAll(() => {
const component = {
clientTimeZoneShiftInMinutes: 180,
};
})
test("Choosing correct shift", () => {
expect(getShift("2022-12-22T00:00:01")).toBe(1);
});

但显然它不起作用。我还尝试在jest.config.js中指定globals,没有运气。

如何模拟这样一个全局可用的对象进行jest测试?

我设法在测试用例中使用以下代码解决了这个问题:

beforeAll(() => {
global.window = Object.create(window);
Object.defineProperty(window, "component", {
value: {clientTimeZoneShiftInMinutes: 180}
,writable: true
});
const component = window.component;
})

最新更新