DEV Community

Kinga
Kinga

Posted on • Edited on

Mock localized strings in SPFx solutions

Let's assume I have a SPFx solution with a component that is using localized strings:

solution structure with localized string

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;
Enter fullscreen mode Exit fullscreen mode

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();

    });
//...
}
Enter fullscreen mode Exit fullscreen mode

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"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

And mock your strings as a constant:

SiteConfig.test.tsx
jest.mock('CorporateDesignApplicationCustomizerStrings', () => {
    return {
        MsgUpdating: "a",
        MsgUpdated: "b"
    }
    { virtual: true }
})

describe("SiteConfig", () => {
    //...
}
Enter fullscreen mode Exit fullscreen mode

Solution found in surajit09's answer

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay