Mock localized strings in SPFx solutions

kkazala

Kinga

Posted on July 20, 2023

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

💖 💪 🙅 🚩
kkazala
Kinga

Posted on July 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related