javascript - 当我使用 Jest 从模拟的 axios 调用返回一些响应时变得不确定

标签 javascript unit-testing jestjs axios

我正在尝试模拟 axios 调用并验证响应,但是当我记录来自模拟 axios 调用的响应时,我得到了 undefined。任何人有任何想法为什么?

用户.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);
   }
}

用户.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 的帖子方法。它看起来像这样:

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

最佳答案

这是没有 __mocks__ 文件夹的解决方案。仅使用 jest.mock()

用户.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);
  });
});

带有覆盖率报告的单元测试结果:

 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

关于javascript - 当我使用 Jest 从模拟的 axios 调用返回一些响应时变得不确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416347/

相关文章:

java - 测试工厂行为

unit-testing - TDD 中的单元测试需要多长时间?

java - 当调用 void 方法时,如何使用 PowerMock/PowerMockito/Mockito 抛出异常?

typescript - Jest 模拟节点模块不适用于 typescript

typescript - 使用 Jest 测试 typescript 异步功能

javascript - 使用 PHP、jQuery 登录网站

javascript - 如何将数组中的表排列成原型(prototype)?

JavaScript循环混合div

javascript - 从 JSON 在单个 Highcharts 图中绘制多个系列

node.js - 清晰的手动模拟 Jest