I thought it should theoretically by possible to mock a custom label differently on a per-test basis. I explored some options involving jest.doMock()
, as described in this StackOverflow thread. But these patterns don't work in LWC. I believe what's happening is the @lwc/jest-transformer
does a one-time transformation per test file based on a jest.mock
call at the top of the file, when you call it as described in the docs.
So unfortunately, I think the best you can do is create multiple test files, one per set of custom label values you want to test for.
For example, for this component...
lwcApp.html
<template>
<div>{label.myLabel}</div>
</template>
lwcApp.js
import { LightningElement, track } from "lwc";
import myLabel from "@salesforce/label/c.My_Label";
export default class LwcApp extends LightningElement {
label = { myLabel };
}
...you can test it like this:
lwcApp_English.test.js
import { createElement } from "lwc";
import LwcApp from "c/lwcApp";
// eslint-disable-next-line no-unused-vars
import myLabel from "@salesforce/label/c.My_Label";
jest.mock("@salesforce/label/c.My_Label", () => ({ default: "My Value" }), {
virtual: true
});
describe("c-lwc-app", () => {
it("displays label in English", () => {
const element = createElement("c-lwc-app", { is: LwcApp });
document.body.appendChild(element);
const div = element.shadowRoot.querySelector("div");
expect(div.textContent).toBe("My Value");
});
});
lwcApp_Spanish.test.js
import { createElement } from "lwc";
import LwcApp from "c/lwcApp";
// eslint-disable-next-line no-unused-vars
import myLabel from "@salesforce/label/c.My_Label";
jest.mock("@salesforce/label/c.My_Label", () => ({ default: "Mi Valor" }), {
virtual: true
});
describe("c-lwc-app", () => {
it("displays label in Spanish", () => {
const element = createElement("c-lwc-app", { is: LwcApp });
document.body.appendChild(element);
const div = element.shadowRoot.querySelector("div");
expect(div.textContent).toBe("Mi Valor");
});
});