如何用 sinon 模拟一个独立的导入函数

How to mock a standalone imported function with sinon

如何用 sinon 模拟这个 axios 导入,然后使用期望?我试过:

 import axios from 'axios';
 axiosMock = sinon.mock(axios);

但期望失败了:

describe('Random test', () => { 
 it('should run the test', async () => { 
    axiosMock.withArgs(sinon.match.any).once(); 
    await getName();
 } 
}

被测函数为:

import axios, { AxiosRequestConfig } from 'axios';

async function getName() {
  const config: AxiosRequestConfig = {
    method: 'GET',
    url: ' someUrl',
    headers: {},
  };
  const res = await axios(config);
  return res;
}

Sinon 不支持从模块导入的存根独立函数。一种解决方案是使用 link-seams. Therefore, we need to use proxyquire 构造接缝。

例如

getName.ts:

import axios, { AxiosRequestConfig } from 'axios';

export async function getName() {
  const config: AxiosRequestConfig = {
    method: 'GET',
    url: 'someUrl',
    headers: {},
  };
  const res = await axios(config);
  return res;
}

getName.test.ts:

import proxyquire from 'proxyquire';
import sinon from 'sinon';

describe('68212908', () => {
  it('should pass', async () => {
    const axiosStub = sinon.stub().resolves('mocked response');
    const { getName } = proxyquire('./getName', {
      axios: axiosStub,
    });
    const actual = await getName();
    sinon.assert.match(actual, 'mocked response');
    sinon.assert.calledWithExactly(axiosStub, {
      method: 'GET',
      url: 'someUrl',
      headers: {},
    });
  });
});

测试结果:

  68212908
    ✓ should pass (1399ms)


  1 passing (1s)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
 getName.ts |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------