简体   繁体   English

如何在执行导入之前在玩笑中模拟全局变量?

[英]How to mock a global variable in jest before import is executed?

The value of epoch is set early, and the function has a closure on it as I dont want to regenerate the value of epoch. epoch 的值是提前设置的,函数有一个闭包,因为我不想重新生成 epoch 的值。

/* index.js */
const epoch = Date.now()

function appVersion() {
  console.log(epoch)
}

export { appVersion }

The issue I encounter is that no matter how I mock the global Date object in my test file, this one would return the value not mocked since the import is executing first.我遇到的问题是,无论我如何模拟测试文件中的全局 Date 对象,该对象都会返回未模拟的值,因为导入首先执行。

How can I mock Date.now() in my test file?如何在我的测试文件中模拟 Date.now()?

The alternative I used for now is to have Date.now() in a separate file and jest.mock the file imported我现在使用的替代方法是将 Date.now() 放在一个单独的文件中,并 jest.mock 导入的文件

/* epoch.js */
const epoch = Date.now()

export = { epoch }
/* index.test.js */
import { appVersion } from './app-version'

jest.mock('./epoch', () => ({
  epoch: '11111111'
})

A common pattern for dealing with dates and other non-deterministic values ( Math.random() for example) is to pass them in as an argument, and give them a default value.处理日期和其他非确定性值(例如Math.random()的常见模式是将它们作为参数传入,并为它们提供默认值。

const defaultEpoch = Date.now();

function appVersion(epoch = defaultEpoch) {
  console.log(epoch)
}

export { appVersion }

This way, the code works as expected, but you now have the ability to pass in a specific value when you're testing, in order to make it deterministic:这样,代码按预期工作,但您现在可以在测试时传入特定值,以使其具有确定性:

import { appVersion } from './app-version'

it('uses epoch value for appVersion', () => {
  const mockEpoch = '11111111';
  const version = appVersion(mockEpoch);
  expect(version).toBe('11111111');
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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