I want to test the following React component
import React, { useContext, useState } from "react";
import { IntlProvider } from "react-intl";
export const Context = React.createContext();
const defaultLocale = navigator.language;
const LocalizationWrapper = (props) => {
const [locale, setLocale] = useState(defaultLocale);
function changeLocale(newLocale) {
setLocale(newLocale);
}
return (
<Context.Provider value={{ locale, changeLocale }}>
<IntlProvider locale={locale}>{props.children}</IntlProvider>
</Context.Provider>
);
};
For this, I have written test
import React from 'react';
import { render, unmountComponentAtNode } from "react-dom";
import { FormattedDate } from "react-intl";
import { act } from "react-dom/test-utils";
import LocalizationWrapper from './localizationWrapper';
let container = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
unmountComponentAtNode(container);
container.remove();
container = null;
});
it("date formatted with default locale", () => {
act(() => {
render(
<LocalizationWrapper >
<FormattedDate value={new Date("2021-04-23")} />
</LocalizationWrapper>, container);
});
expect(container.textContent).toBe("4/23/2021");
});
How to add a test case that changes the locale
that is part of LocalizationWrapper
state, by using context or by changing state directly? From code outside of test I use context to change locale like so:
const context = useContext(Context);
context.changeLocale(locale);