本文介绍了当我从使用jest的模拟axios调用返回一些响应时变得不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图模拟axios调用并验证响应,但是当我记录来自模拟axios调用的响应时,我得到了undefined.有人有什么想法吗?

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

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

此外,我只想清除它,即在我的src目录下有一个 mocks 文件夹,其中有一个名为axios.js的文件,在其中嘲笑了axios的帖子方法.看起来像这样:

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: {} }))
};

推荐答案

这是不带__mocks__文件夹的解决方案.仅使用jest.mock().

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

源代码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59416347

这篇关于当我从使用jest的模拟axios调用返回一些响应时变得不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 16:11