3

尝试测试axios呼叫并尝试moxios包。

"axios": "^0.16.2", "moxios": "^0.4.0",

在这里找到:https ://github.com/axios/moxios

按照那里的例子,但我的测试错误就moxios.install()行了:

import axios from 'axios'
import moxios from 'moxios'
import sinon from 'sinon'
import { equal } from 'assert'

describe('mocking axios requests', function () {

  describe('across entire suite', function () {

    beforeEach(function () {
      // import and pass your custom axios instance to this method
      moxios.install()
    })

我的实际测试

import axios from 'axios';
import moxios from 'moxios';
import sinon from 'sinon';
import { equal } from 'assert';

const akamaiData = {
  name: 'akamai'
};

describe('mocking axios requests', () => {
  describe('across entire suite', () => {
    beforeEach(() => {
      // import and pass your custom axios instance to this method
      moxios.install();
    });

    afterEach(() => {
      // import and pass your custom axios instance to this method
      moxios.uninstall();
    });

    it('should stub requests', (done) => {
      moxios.stubRequest('/akamai', {
        status: 200,
        response: {
          name: 'akamai'
        }
      });

      // const onFulfilled = sinon.spy();
      // axios.get('/akamai').then(onFulfilled);
      //
      // moxios.wait(() => {
      //   equal(onFulfilled.getCall(0).args[0], akamaiData);
      //   done();
      // });
    });
  });
});

在此处输入图像描述

我确实在这里找到了这个已关闭的问题,但是修复“传递axiosmoxios.install(axios)函数不起作用”

https://github.com/axios/moxios/issues/15

4

2 回答 2

8

我遇到了同样的问题。原来我的axios.js文件__mocks__夹中有一个文件(模拟 axios 的不同尝试留下的)。该模拟文件接管了实际的 axios 代码——但 moxios 需要真正的axios 代码才能正常运行。当我axios.js__mocks__文件夹中删除文件时,moxios 就像宣传的那样工作。

于 2018-04-02T18:45:28.793 回答
-3

原来我不需要moxios,在我的测试中我不想进行实际的 API 调用......只需要确保调用该函数。用测试功能修复它。

import { makeRequest } from 'utils/services';
import { getImages } from './akamai';

global.console = { error: jest.fn() };

jest.mock('utils/services', () => ({
  makeRequest: jest.fn(() => Promise.resolve({ data: { foo: 'bar' } }))
}));

describe('Akamai getImages', () => {
  it('should make a request when we get images', () => {
    getImages();
    expect(makeRequest).toHaveBeenCalledWith('/akamai', 'GET');
  });
});
于 2018-04-05T19:01:42.897 回答