用玩笑进行多环境测试
Multiple environment testing with 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')
})
})
})
我的 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')
})
})
})