Getting undefined when I return some response from mocked axios call using jest

北城以北 提交于 2019-12-23 22:26:56

问题


I'm trying to mock axios call and verify the response, but when I log the response from mocked axios call, I'm getting undefined. Anyone have any ideas why?

users.js

import axios from 'axios';

export default class MyClass{
   constructor(config){
      this.config = config;
   }

   async getUsers(url, params, successHandler, errorHandler) {
      return axios.post(url, params)
             .then(resp => this.handleAPIResponse.call(this, resp, successHandler, errorHandler))
             .catch(error => errorHandler);
   }
}

users.test.js

import MyClass from './mycode.js';
import axios from 'axios';

jest.mock('axios');

beforeEach(() => {
  myClass = new MyClass({ env: 'prod' });
});

afterEach(() => {
  jest.clearAllMocks();
});

const mockResponseData = jest.fn((success, payload) => {
  return {
    data: {
      result: {
        success,
        payload
      }
    }
  };
});

test('should return all the users', async () => {
   const successHandler = jest.fn();
   const errorHandler = jest.fn();
   const users = mockResponseData(true, ['John Doe', 'Charles']);

   axios.post.mockImplementationOnce(() => {
     return Promise.resolve(users);
   });

   const response = await myClass.getUsers('url', {}, successHandler, errorHandler);
   console.log(response);  // This logs undefined
   expect(successHandler).toHaveBeenCalledTimes(1);
});

Also, I just want to clear it out that I've a mocks folder just under my src directory inside which I've a file named axios.js where I've mocked axios' post method. It looks like this:

export default {
  post: jest.fn(() => Promise.resolve({ data: {} }))
};

回答1:


Here is the solution without __mocks__ folder. Only use jest.mock().

users.js

import axios from 'axios';

export default class MyClass {
  constructor(config) {
    this.config = config;
  }

  async getUsers(url, params, successHandler, errorHandler) {
    return axios
      .post(url, params)
      .then((resp) => this.handleAPIResponse.call(this, resp, successHandler, errorHandler))
      .catch((error) => errorHandler);
  }

  async handleAPIResponse(resp, successHandler, errorHandler) {
    successHandler();
    return resp;
  }
}

users.test.js:

import MyClass from './users';
import axios from 'axios';

jest.mock('axios', () => {
  return {
    post: jest.fn(() => Promise.resolve({ data: {} })),
  };
});

describe('59416347', () => {
  let myClass;
  beforeEach(() => {
    myClass = new MyClass({ env: 'prod' });
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  const mockResponseData = jest.fn((success, payload) => {
    return {
      data: {
        result: {
          success,
          payload,
        },
      },
    };
  });

  test('should return all the users', async () => {
    const successHandler = jest.fn();
    const errorHandler = jest.fn();
    const users = mockResponseData(true, ['John Doe', 'Charles']);

    axios.post.mockImplementationOnce(() => {
      return Promise.resolve(users);
    });

    const response = await myClass.getUsers('url', {}, successHandler, errorHandler);
    console.log(response);
    expect(response.data.result).toEqual({ success: true, payload: ['John Doe', 'Charles'] });
    expect(successHandler).toHaveBeenCalledTimes(1);
  });
});

Unit test result with coverage report:

 PASS  src/stackoverflow/59416347/users.test.js (9.166s)
  59416347
    ✓ should return all the users (18ms)

  console.log src/stackoverflow/59416347/users.test.js:41
    { data: { result: { success: true, payload: [Array] } } }

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |    90.91 |      100 |    83.33 |    90.91 |                   |
 users.js |    90.91 |      100 |    83.33 |    90.91 |                12 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.518s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59416347



来源:https://stackoverflow.com/questions/59416347/getting-undefined-when-i-return-some-response-from-mocked-axios-call-using-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!