【问题标题】:How to mock a standalone imported function with sinon如何使用 sinon 模拟独立的导入函数
【发布时间】:2021-09-13 16:23:59
【问题描述】:

如何使用 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;
}

【问题讨论】:

  • 您使用的是什么测试runnerjestmochaava,还有别的吗?

标签: typescript mocking sinon


【解决方案1】:

Sinon 不支持从模块导入的 stub 独立函数。一个解决方案是使用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 |                   
------------|---------|----------|---------|---------|-------------------

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2021-11-27
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2018-08-28
    • 1970-01-01
    相关资源
    最近更新 更多