Moxios - TypeError:无法读取属性' adapter'未定义的

时间:2018-03-21 18:47:33

标签: testing axios moxios

尝试测试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();
      // });
    });
  });
});

enter image description here

我确实在这里找到了这个已关闭的问题,但是修复"将axios传递到moxios.install(axios)功能不起作用"

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

2 个答案:

答案 0 :(得分:3)

我遇到了同样的问题。事实证明我在axios.js文件夹中有一个__mocks__文件(从另一个模拟axios的尝试中删除)。该模拟文件接管了实际的axios代码 - 但是moxios需要真正的 axios代码才能正常运行。当我从axios.js文件夹中删除__mocks__文件时,moxios按宣传方式工作。

答案 1 :(得分:0)

原来我不需要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');
  });
});