2

I am mocking the values in a custom label using this from

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.unit_testing_using_jest_patterns

import myImport from '@salesforce/label/c.specialLabel';

jest.mock('@salesforce/label/c.specialLabel', () => {
return { default: "value set in test" };
}, { virtual: true });`

However, I need to change the mocked value again to test another method , is it possible to change the mocked value returned multiple times.

1 Answer 1

1

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");
  });
});

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .