I have a component that looks like this:
const isPersonalSite: boolean = process.env.PERSONAL_SITE === 'true';
const isFeatureEnabled: boolean = process.env.IS_FEATURE_ENABLED === 'true';
export const ProfileMenu = () => {
console.log('PERSONAL_SITE component', process.env.PERSONAL_SITE)
return (
<>
{!isPersonalSite && isFeatureEnabled &&
<a href="http://test.com">Test 1</a>
}
{!isPersonalSite && !isFeatureEnabled &&
<a href="http://test2.com">Test 2</a>
}
{isPersonalSite &&
<a href="http://test3.com">Test 3</a>
}
<a href="/logout">Logout</a>
</>
)
}
and I am trying to write a test using JestJS. My jest.config.js
contains the following definition after module.exports
:
process.env = Object.assign(process.env, {
PERSONAL_SITE: false,
IS_FEATURE_ENABLED: false
});
The test looks like this:
describe("ProfileDropDownMenu", () => {
const env = process.env
beforeEach(() => {
jest.resetModules()
process.env = { ...env }
})
afterEach(() => {
process.env = env
})
it('render the menu', () => {
process.env.PERSONAL_SITE = 'true'
console.log('PERSONAL_SITE test', process.env.PERSONAL_SITE)
render(
<ProfileMenu />
)
expect(screen.getByText('Test 3')).toBeInDocument();
expect(screen.getByText('Logout')).toBeInDocument();
})
})
From the above, I would expect the test to pass, but it is failing instead saying that Test 3
does not exist in the document and I wonder why. PERSONAL_SITE test
prints out true
. PERSONAL_SITE component
also prints out true
but the test won’t pass, why?
2
Answers
I think the problem is a typo
it is
.toBeInTheDocument()
instead of.toBeInDocument()
I tried same code you provided and the Test pass.
Hope this helps
isPersonalSite
andisFeatureEnabled
are declared outside the functionProfileMenu
. In fact, those two const are declared outside of any function.What does it mean ? It means that their value is calculated when the file is read, so when it is imported.
So, when you are calling
ProfileMenu
,isPersonalSite
andisFeatureEnabled
are already set totrue
/false
(it looks like it’sfalse
in this case).How to fix this ? There are multiple ways :
Set the declaration of the two constants inside the function
ProfileMenu
Import your component dynamically after setting process.env with
import()
orrequire()
Use jest setup files, you could prepare your testing environment (global mocks, global env vars) before executing tests : https://jestjs.io/docs/configuration#setupfiles-array
Each way has pros and cons depending on what you want to achieve. I’d avoid the 1st one because you shouldn’t edit your codebase to make tests pass, but in some cases you may need to code in a way that will simplify testing for you.