DEV Community

Kinga
Kinga

Posted on • Updated 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

Top comments (0)