首页 > 解决方案 > 使用 jest 进行多环境测试

问题描述

我的 React 应用程序中有一些环境变量放在.env.development文件中,它们会更改应用程序逻辑和视图,例如:REACT_APP_USER_SIGN_UP_ENABLED=true.

我可以配置 Jest 配置或某些测试来测试每个场景,在哪里REACT_APP_USER_SIGN_UP_ENABLED=trueREACT_APP_USER_SIGN_UP_ENABLED=false

标签: reactjstestingautomated-testsjestjse2e-testing

解决方案


您可以临时更改环境变量

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')
        })
    })
})

推荐阅读