axios Moxios -类型错误:无法读取未定义的属性“adapter”

o75abkj4  于 2023-01-13  发布在  iOS
关注(0)|答案(3)|浏览(205)

正在尝试测试axios调用和moxios包。
x1米2英寸x1米3英寸
在此处找到: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

vmdwslir

vmdwslir1#

我遇到了同样的问题。原来我的__mocks__文件夹中有一个axios.js文件(另一次尝试模仿axios时遗留下来的)。这个模仿文件接管了实际的axios代码--但是mixos需要 * 真实的 * axios代码才能正常工作。当我从__mocks__文件夹中删除axios.js文件时,mixos就像广告中说的那样工作了。

6za6bjd0

6za6bjd02#

对我来说,这是关于ES模块互操作的。尝试以下两种变通方法之一:

  • 尝试将import moxios from 'moxios'更改为import * as moxios from 'moxios'
  • tsconfig.json中将esModuleInterop设置为true
xlpyo6sf

xlpyo6sf3#

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

相关问题