【问题标题】:Multiple environment testing with jest使用 jest 进行多环境测试
【发布时间】:2018-11-08 21:48:15
【问题描述】:
我的 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?
【问题讨论】:
标签:
reactjs
testing
automated-tests
jestjs
e2e-testing
【解决方案1】:
你可以临时改变环境变量
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')
})
})
})