admin管理员组

文章数量:1134557

I'm new to JEST and I'm currently testing a Javascript component that makes an API call in its onComponentDidMount. Depending on the return data of the ajax call (api call) my component either display a table or a simple text.

My JEST test are fairly simple, for now I'm only testing to match the current snapshots. So since my api call can return different data, my snapshot can be of two different aspects : 1) one with a table 2) one with a simple text.

I successfully mocked the service like that

jest.mock("/myService", () => ({
  index: (data, callback) => {
    const return = [
      {
        {...}
      },
    ]
    callback(return)
  },
}))

My component does the myService.index() call correctly, all I wish to pass to it different values which its gonna use to make the callback.

Here's how the it looks like

it("has proper snapshot", () => {
    const props = {...}
    const component = shallow(<MyComponent {...props} />)
    expect(component).toMatchSnapshot()
  })

This works great for the first exemple but I cannot seem to find a correct answer that suits me. Can you help me ? :)

I'm new to JEST and I'm currently testing a Javascript component that makes an API call in its onComponentDidMount. Depending on the return data of the ajax call (api call) my component either display a table or a simple text.

My JEST test are fairly simple, for now I'm only testing to match the current snapshots. So since my api call can return different data, my snapshot can be of two different aspects : 1) one with a table 2) one with a simple text.

I successfully mocked the service like that

jest.mock("/myService", () => ({
  index: (data, callback) => {
    const return = [
      {
        {...}
      },
    ]
    callback(return)
  },
}))

My component does the myService.index() call correctly, all I wish to pass to it different values which its gonna use to make the callback.

Here's how the it looks like

it("has proper snapshot", () => {
    const props = {...}
    const component = shallow(<MyComponent {...props} />)
    expect(component).toMatchSnapshot()
  })

This works great for the first exemple but I cannot seem to find a correct answer that suits me. Can you help me ? :)

Share Improve this question edited Dec 21, 2018 at 15:55 Simon Leyendecker asked Dec 21, 2018 at 15:21 Simon LeyendeckerSimon Leyendecker 1,1632 gold badges7 silver badges6 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 279

1- If you want the mock to return different results on each call:

Use mockReturnValueOnce

myMock
  .mockReturnValueOnce(10)
  .mockReturnValueOnce('x')
  .mockReturnValue(true);

will return 10 on the first call, 'x' on the second call and true anytime after that.

2- If you want to check the arguments that the mock has been called with:

Use toHaveBeenNthCalledWith

expect(mock).toHaveBeenNthCalledWith(1, '1st call args');
expect(mock).toHaveBeenNthCalledWith(2, '2nd call arg 1', '2nd call arg 2');

will assert that

  • the mock was called with '1st call args' the first time it was called -> mock('1st call args')

  • the mock was called with '2nd call arg 1' and '2nd call arg 2' the second time it was called -> mock('2nd call arg 1', '2nd call arg 2')

3- If you want a specific response based on the function parameter

It is not supported by jest by default but you can have a look at jest-when which allows you to do something like:

when(fn).calledWith(1).mockReturnValue('yay!')

This is how we can mock the same function twice with different arguments:

Import the Axios:

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

Use the mockedAxios:

const mock = jest.spyOn(mockedAxios, 'post');
mock.mockImplementation((url): any => {
  if (url.indexOf('checkAddOnEligibility') > 0) {
    return { data: [{ validationMessage: { value: '' }, isValid: { value: true } }] };
  }
  return {
    data: [
      {
        something: 48945
      },
    ],
  };
});

Building on @klugjo's answer, there is a way to return different mocks for the same module/function depending on the parameters passed without using any external libraries like jest-when.

For example, suppose you have a function to get the values for certain app configs:

function getAppConfig(configName) {
  /* Return the config for the provided configName */
}

In my testing, I wanted to mock different values for different configs, and didn't want to cause chaos with using the mock.mockReturnValueOnce().mockReturnValueOnce() type of pattern. This also causes a heavy dependency with your tests relying on a specific order of calls, which makes it harder to maintain them.

Instead I did something like this:

Test File

//these will be used to mock values for various configs
const mockConfigA = jest.fn();
const mockConfigB = jest.fn();

// this will return the appropriate mocked value based on the requested config
const mockAppConfig = (configName) => {
  switch (configName) {
    case 'A':
      return mockConfigA();
    case 'B':
      return mockConfigB();
  }
}

// mock the module with the "dynamic" mocker
jest.mock('..path/to/config', () => {
  return mockAppConfig;
})

This makes it so that you can write cleaner tests for each scenario returned from the config!

describe('Something', () => {
  beforeEach(() =>{
    mockConfigA.mockReturnValue('A');
    mockConfigB.mockReturnValue('B');
  });
  test('When Config A returns X', () => {
    mockConfigA.mockReturnValue('X');
    // do the test for config A returning X, B returning B
  });
  test('When Config B returns Y', () => {
    mockConfigB.mockReturnValue('Y');
        // do the test for config B returning Y, A returning A

  });
});

Please check the Jest docs on this. You can return different values when mocking a function and once return a value you wish and then later a different value.

本文标签: javascriptJest mock the same function twice with different argumentsStack Overflow