Let's assume I have a SPFx solution with a component that is using localized strings:
SiteConfig.tsx
import strings from 'CorporateDesignApplicationCustomizerStrings';
const SiteConfig: React.FunctionComponent<ISiteConfigProps> = (props) => {
const [msgTxt, setMsgTxt] = React.useState<string>();
setMsgTxt(strings.MsgUpdating) //"Few more things. We are now updating site logo and creating a few pages. Please wait.");
return (<>
{ msgTxt &&
<MessageBar data-testid="messagebar">
{
<div dangerouslySetInnerHTML={{ __html: msgTxt }} />
}
</MessageBar>
}
</>);
}
export default SiteConfig;
My test is rather simple:
SiteConfig.test.tsx
describe("SiteConfig", () => {
let mockPageContext: PageContext;
let mockSPFI: SPFI;
let siteConfig: RenderResult;
it("should render correctly", async () => {
await act(async () => {
siteConfig = render(<SiteConfig />);
});
expect(siteConfig.getByTestId('messagebar')).toBeInTheDocument();
});
//...
}
The problem
And the result... is FAIL: Cannot find module 'CorporateDesignApplicationCustomizerStrings' from 'src/extensions/corporateDesign/components/SiteConfig/SiteConfig.tsx'
The solution
The solution is an extremely easy one.
Add "CorporateDesignApplicationCustomizerStrings": "identity-obj-proxy"
line in package.json
:
package.json
{
//...
"jest": {
"moduleNameMapper": {
"CorporateDesignApplicationCustomizerStrings": "identity-obj-proxy"
}
}
}
And mock your strings as a constant:
SiteConfig.test.tsx
jest.mock('CorporateDesignApplicationCustomizerStrings', () => {
return {
MsgUpdating: "a",
MsgUpdated: "b"
}
{ virtual: true }
})
describe("SiteConfig", () => {
//...
}
Solution found in surajit09's answer
Top comments (0)