I am working on a NextJS+React project and need to write a Unit Test using JestJS that depends on one ENV variable. The variables is named to SITE_BRAND
and defaulted to brand
value.
This is what the test looks like:
import {SignUp} from '@modules/sign-up'
import { render, screen } from '@testing-library/react'
describe('Sign Up page', () => {
beforeEach( () => {
jest.resetModules()
})
it('should render sign up form', () => {
process.env.SITE_BRAND = 'brand1';
render(<SignUp pageData={pageData} />)
expect(screen.getByTestId('link-login')).toBeInTheDocument();
})
})
The above expectation does fail if SITE_BRAND !== brand1
which is my issue because the ENV will not change after the component is imported which is my case.
I have Google this and found a few posts: 1, 2 and 3 and following the accepted answer on 2 I changed the test to this:
import { render, screen } from '@testing-library/react'
describe('Sign Up page', () => {
beforeEach( () => {
jest.resetModules()
})
it('should render sign up form', () => {
process.env.SITE_BRAND = 'brand1';
const SignUp = require('../Signup');
render(<SignUp pageData={pageData} />)
expect(screen.getByTestId('link-login')).toBeInTheDocument();
})
})
but the test fails with the following error:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
I also did Google the above issue but could not find anything helpful.
The component is exported as default:
const SignUp = () => { .... }
export default SignUp
How can I use a custom value for the ENV variable and test the component properly?