j obe
j obe

Reputation: 2049

Difficulty understanding mocked Jest functions

I have a test file to test a React component.

The React component uses some helper functions to calculate some things, e.g. takes in a customer's date of birth and returns a number based on if their age is in a certain range.

In the test file, I am passing these values in so the test will pass for today, but I need to mock it so that always passes.

I understand that I need to mock the helper function that is being imported in the component, but I just can't figure this out.

A component code example is

import { ageFunc } from './mydir/helper/ageFunc';

Then it's used with some props passed into the component:

const ageRange value = ageFunc(customerPropValues);

This ageRange value then decides whether to render something or not.

In the test file I am passing valid customer birthdate values, to trigger the rendering behaviour I expect. How do I set this up with mocks?

Upvotes: 0

Views: 707

Answers (1)

Antonio Erdeljac
Antonio Erdeljac

Reputation: 3244

I am not sure if I understood it entirely, but if you need to mock it so it always work, you should mock the implementation so it always returns the same thing. You can find out a lot about mocking custom functions here.

// Mock before importing
jest.mock('./mydir/helper/ageFunc', () => ({
  __esModule: true,
  default: () => 'Default',
  ageFunc : () => 'hardcoded result',
}));
import { ageFunc } from './mydir/helper/ageFunc';

const ageRange = ageFunc(customerPropValues); // ageRange returns 'Hardcode result'

If this is not the case, you want, but just want to check whether the right arguments are being passed, or the right result is received, you can do some of the following:

// The mock function was called at least once
expect(ageFunc).toHaveBeenCalled();

// The mock function was called at least once with the specified arguments
expect(ageFunc).toHaveBeenCalledWith(arg1, arg2);

// The last call to the mock function was called with the specified arguments
expect(ageFunc).toHaveBeenLastCalledWith(arg1, arg2);

// All calls and the name of the mock is written as a snapshot
expect(ageFunc).toMatchSnapshot();

Helpful links: link #1 link #2

How does it work?

Let's start with a simple example of a default module:

import a from './path'

The way we would mock this would be:

jest.mock('./path')
import a from './path'

This the test file will read a mocked function into the a variable.

Now for your case you've got a named export, so the case is a bit more complex.

import { a } from './path'

To mock this, we have to extend jest.mock a bit.

jest.mock('./path', () => ({
      __esModule: true, // Settings to make it behave as an ECMAScript module
      default: () => 'Default', // Mock the default export (import a from './dir')
      a: () => 'hardcoded result', // Mock the named export (import { a } from './dir'
    }));

Upvotes: 1

Related Questions