Home > Web Front-end > JS Tutorial > Mocking Constants in Tests with Jest: A Practical Example

Mocking Constants in Tests with Jest: A Practical Example

Barbara Streisand
Release: 2025-01-11 08:53:42
Original
276 people have browsed it

Mockando Constantes em Testes com Jest: Um Exemplo Prático

When working with constants in your projects, it is sometimes necessary to change their values ​​to test different scenarios. However, directly imported constants cannot be easily overwritten, which can make test creation difficult. In this article, we will see how to use Jest to dynamically mock constants, ensuring isolated and reliable tests.

Let's create a fictitious example called adjustImageQuality, where we adjust the quality of an image depending on whether we are in a production environment.


Implementation

constants.js file

We define a constant called IS_PRODUCTION that indicates whether we are in a production environment:

// constants.js
export const IS_PRODUCTION = false;
Copy after login

adjustImageQuality.js file

Now, we create the adjustImageQuality function. It changes the image quality only if the system is in production:

// adjustImageQuality.js
import { IS_PRODUCTION } from "./constants";

export default function adjustImageQuality(img) {
  if (IS_PRODUCTION) {
    img.quality = 100; // Qualidade máxima em produção
  } else {
    img.quality = 50; // Qualidade reduzida em desenvolvimento
  }

  return img;
}
Copy after login

Writing the Tests

We want to test the behavior of adjustImageQuality for both scenarios: production (IS_PRODUCTION = true) and development (IS_PRODUCTION = false).

adjustImageQuality.test.js file

We use Jest to dynamically mock the value of IS_PRODUCTION. The secret is to use jest.mock and override the constant with a custom getter.

// adjustImageQuality.test.js
import adjustImageQuality from "./adjustImageQuality";

// Mock para a constante IS_PRODUCTION
const mockIsProduction = jest.fn();

jest.mock("./constants", () => {
  const constants = jest.requireActual("./constants");
  return {
    ...constants,
    get IS_PRODUCTION() {
      return mockIsProduction();
    },
  };
});

beforeEach(() => {
  mockIsProduction.mockClear(); // Limpa os mocks antes de cada teste
});

test("sets image quality to 100 in production", () => {
  // Configura o mock para retornar true (produção)
  mockIsProduction.mockReturnValue(true);

  const img = { quality: 0 };

  const result = adjustImageQuality(img);

  expect(result.quality).toEqual(100);
});

test("sets image quality to 50 in development", () => {
  // Configura o mock para retornar false (desenvolvimento)
  mockIsProduction.mockReturnValue(false);

  const img = { quality: 0 };

  const result = adjustImageQuality(img);

  expect(result.quality).toEqual(50);
});
Copy after login

Mock Explanation

1. Creating the Mock

We use jest.mock to intercept the constants module. Inside it, we use jest.requireActual to get the actual exports and add a getter for the constant IS_PRODUCTION.

jest.mock("./constants", () => {
  const constants = jest.requireActual("./constants");
  return {
    ...constants,
    get IS_PRODUCTION() {
      return mockIsProduction();
    },
  };
});
Copy after login

2. Mocking the Value of IS_PRODUCTION

Within each test, we use mockReturnValue to simulate different values ​​for IS_PRODUCTION:

  • mockIsProduction.mockReturnValue(true) for production.
  • mockIsProduction.mockReturnValue(false) for development.

3. Cleaning with mockClear

Before each test, we clear the mock state to ensure it doesn't interfere with other tests:

beforeEach(() => {
  mockIsProduction.mockClear();
});
Copy after login

Conclusion

This mock pattern for constants allows you to dynamically control values ​​used in your application logic, ensuring isolated and reliable tests. It is especially useful when you need to test behaviors based on global variables, configurations, or system states.

With this approach, you can cover complex scenarios without compromising the structure of your code or adding unnecessary external dependencies.

The above is the detailed content of Mocking Constants in Tests with Jest: A Practical Example. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template