reactjs - 使用 jest 进行多环境测试
问题描述
我的 React 应用程序中有一些环境变量放在.env.development
文件中,它们会更改应用程序逻辑和视图,例如:REACT_APP_USER_SIGN_UP_ENABLED=true
.
我可以配置 Jest 配置或某些测试来测试每个场景,在哪里REACT_APP_USER_SIGN_UP_ENABLED=true
和REACT_APP_USER_SIGN_UP_ENABLED=false
?
解决方案
您可以临时更改环境变量
process.env.VARIABLE_TO_CHANGE = 'newvalue'
这是它的快速演示:
.env
ENV_VARIABLE=value
EnvReader.js
const read = () => {
return process.env.ENV_VARIABLE
}
module.exports = {
read
}
EnvReader.test.js
require('dotenv').config()
const read = require('./EnvReader').read
describe('tests', () => {
it('can read environment variables', () => {
expect(read()).toEqual('value')
})
describe('by changing environment variables', () => {
let originalValue
beforeAll(() => {
originalValue = process.env.ENV_VARIABLE
process.env.ENV_VARIABLE = 'othervalue'
})
afterAll(() => {
process.env.ENV_VARIABLE = originalValue
})
it('can read the new value', () => {
expect(read()).toEqual('othervalue')
})
})
describe('after messing with environment variables', () => {
it('can still read the original value', () => {
expect(read()).toEqual('value')
})
})
})
推荐阅读
- javascript - React Native 中 ViewPager 中子组件的 React createRef
- hyperledger-fabric - 使用 CURL 访问超级账本结构
- android - AccessibilityManagerService 的一个错误
- multithreading - DispatchQueue.main.async 不返回主线程 - SwiftUI
- javascript - 如何在 jQuery&Javascript Mvc 上使用其他参数上传
- python - 我的 for 循环中的计数器有什么问题?
- google-chrome - 使用脚本在 Chrome 上剪切和粘贴
- python - 如何在 django 中使用电话号码实现两步注册?
- javascript - Vue.js 分页计算未按预期工作
- javascript - 反应:为每个孩子添加一个事件侦听器并将一个引用传递给父母的事件处理程序 - 效率低吗?事件冒泡可能吗?