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

问题描述 投票:0回答:1

我如何用 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;
}
typescript axios mocking sinon
1个回答
1
投票

Sinon 不支持从模块导入存根独立函数。解决方案是使用link-seams。因此,我们需要使用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 |                   
------------|---------|----------|---------|---------|-------------------
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.