I need to test whether a component is rendered properly based on cookies. In the element are a few conditionals checking on some cookies values and outputting accordingly and this is what I am trying to test with JestJS.
Since this is a React+NextJS project I am using the cookies-next
package. This is what I am doing in my test:
jest.mock('cookies-next', () => {
__esModule: true,
getCookies: jest.fn()
})
const mockedGetCookies = getCookies as jest.Mock<>
describe('Testing the component', () => {
it('will render correct HTML based on cookies', () => {
mockedGetCookies.mockReturnValue([
{locale: 'en-us', countryCode: 'US'},
jest.fn(),
jest.fn()
])
<MyComponent />
// assertions
})
})
The above test will pass but if I change the value of the cookie in another test it does not pass:
describe('Testing the component', () => {
it('will render correct HTML based on cookies', () => {
mockedGetCookies.mockReturnValue([
{locale: 'en-gb', countryCode: 'UK'},
jest.fn(),
jest.fn()
])
<MyComponent />
// assertions here are different than before because it is supposed the cookies are set differently
})
})
The component does a few checks using the value from the cookie. This is an snippet so you can understand what I am trying to test:
import { getCookies } from 'cookies-next'
const MyComponent = () => {
const { locale, countryCode } = getCookies()
let outputHtml
if (locale == 'en-us' && countryCode == 'US') {
outputHtml = <div>US</div>
} else if (locale == 'en-gb' && countryCode == 'UK') {
outputHtml = <div>UK</div>
} else {
outputHtml = <div>Others</div>
}
}
export default MyComponent
if I use screen.debug()
both tests render <div>US</div>
which means the cookie is not being mocked/set properly.
What am I missing here?