开玩笑地进行多环境测试

时间:2018-07-12 13:04:39

标签: reactjs testing automated-tests jestjs e2e-testing

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

我可以配置Jest配置或某些测试来测试每个场景,其中REACT_APP_USER_SIGN_UP_ENABLED=trueREACT_APP_USER_SIGN_UP_ENABLED=false吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下方式临时更改环境变量

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')
        })
    })
})
相关问题