Reputation:
I am trying to test a spfx webpart component and I am getting the following error:
Test suite failed to run
Cannot find module 'WebPartContentStrings' from 'WebContentContainer.tsx'
I did some digging and I found that inside my component I do the following:
import * as strings from "WebPartContentStrings";
And I have this file:
declare module 'WebPartContentStrings' {
const strings: IWebPartContentStrings;
export = strings;
}
However, it seems when I mock the component Jest cannot interpret the import instruction correctly and cannot find the module even though the application can find it when I host it on a server. Is there a way to import the strings in a different way for Jest?
Upvotes: 1
Views: 1340
Reputation: 1
Instead of doing
import * as strings from "WebPartContentStrings";
pass the strings of your webpart as props to the component and use those the way you use normal props. For example:
Props interface definition:
export interface IYourComponentsProps { strings: IWebPartContentStrings }
Using some of the strings in your react component's render function:
<p>{this.props.strings.exampleString}</p>
This will fix the import issue you're facing.
Cheers.
Upvotes: 0
Reputation: 590
I had the same problem.It has to be fixed when 'react' the 'jsx' property in tsconfig.json.
For example:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"types": ["jest", "node"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"strict": true,
"noEmit": true,
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"isolatedModules": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
]
}
Upvotes: 1