I’m loading a script for 3rd party cookie management using the <Script />
component. I want to test that it was loaded with correct language attribute. But I don’t know how to test it.
RootLayout:
layout.tsx
const RootLayout = ({
children,
}: PropsWithChildren) => {
return (
<html className={rubikVariable.variable} lang={language}>
<UserProvider>
<CookieInformation>
<body className="body">
...
</body>
</CookieInformation>
<UserProvider>
<html>
)
})
CookieInformation.tsx
'use client';
import Script from 'next/script';
import { PropsWithChildren } from 'react';
const CookieInformation = ({ children }: PropsWithChildren) => {
const browserLang = navigator.language;
// extracts language, ex. 'en-us' -> 'en'
const matches = browserLang.match(/w*(?=-)?/i);
const language = matches?.[0] ?? 'en';
return (
<>
<Script
data-testid="cookie-script"
data-culture={language}
data-testid="cookie-information-script"
id="CookieConsent"
src="https://policy.app.cookieinformation.com/uc.js"
strategy="lazyOnload"
/>
{children}
</>
);
};
export default CookieInformation;
cookie-information.test.tsx
describe('CookieInformation', () => {
it('should call 3rd party script with language from user agent', () => {
const expected = 'https://policy.app.cookieinformation.com/uc.js'
// mock language
Object.defineProperty(global.navigator, 'language', {
value: 'en-gb'
});
jest.mock('next/script', () => {
// eslint-disable-next-line react/display-name, react/prop-types
return function ({ children, 'data-testid': dataTestId, ...props }) {
return (
<script data-testid={dataTestId} {...props}>
{children}
</script>
);
};
});
render(
<CookieInformation />
);
expect(document.querySelector('script)).toHaveAttribute(
'src',
expected
);
// expect(getByTestId('cookie-script')).toHaveAttribute('src', expected);
});
})
But the test can’t find the script and query always returns null
. Doesn’t matter if I remove the mock of ‘next/script’. Doesn’t matter if I query by test id or directly on the document.
Doing screen.debug
also reveals that script are not present in test DOM.
So how can I test that script is there and have correct attributes?