【问题标题】:Sinon stub axios throws error : TypeError: Attempted to wrap get which is already wrappedSinon stub axios 抛出错误:TypeError: Attempted to wrap get which has been Wrapped
【发布时间】:2020-05-10 17:20:31
【问题描述】:

目前很少有关于堆栈溢出的问题出现此错误,但没有一个问题解释了存根axios 上的此错误。我从 sinonjs.org 获取了样板工作示例,并尝试模拟 axios。它抛出错误

TypeError: Attempted to wrap get which has been Wrapped

代码如下:

import Axios from 'axios';

var sandbox = require('sinon').createSandbox();

describe('axios.get method', function () {
  beforeEach(function () {
    // stub out the `axios` method
    sandbox.stub(Axios, 'get');
  });

  afterEach(function () {
    // completely restore all fakes created through the sandbox
    sandbox.restore();
  });

  it('should be called once', function () {});
});

【问题讨论】:

    标签: axios sinon stubbing


    【解决方案1】:

    您收到此错误的原因是您多次存根Axios.get 方法。您提供的代码工作正常。因此,您需要调用sanbox.restore() 方法来恢复通过沙箱创建的所有伪造品,然后再重新存根该方法。请检查您的代码不会继续存根 Axios.get 方法。

    例如

    index.test.ts:

    import Axios from 'axios';
    import sinon from 'sinon';
    const sandbox = sinon.createSandbox();
    
    describe('axios.get method', () => {
      let axiosGetStub;
      beforeEach(() => {
        axiosGetStub = sandbox.stub(Axios, 'get');
      });
    
      afterEach(() => {
        sandbox.restore();
      });
    
      it('should be called once', () => {
        Axios.get('http://localhost:3000');
        sandbox.assert.calledOnce(axiosGetStub);
      });
      it('should be called once again', () => {
        Axios.get('http://localhost:3000');
        sandbox.assert.calledOnce(axiosGetStub);
      });
    });
    

    单元测试结果:

      axios.get method
        ✓ should be called once
        ✓ should be called once again
    
    
      2 passing (29ms)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 2023-03-17
      • 2016-04-02
      • 1970-01-01
      • 2013-05-04
      • 2014-02-26
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多