【问题标题】:Moxios - TypeError: Cannot read property 'adapter' of undefinedMoxios - TypeError:无法读取未定义的属性“适配器”
【发布时间】:2018-08-31 01:08:30
【问题描述】:

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

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

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

【问题讨论】:

    标签: testing axios moxios


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 2022-01-01
        • 2022-07-12
        • 2022-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2020-11-29
        相关资源
        最近更新 更多