簡體   English   中英

如何使用 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 因此,我們需要使用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 |                   
------------|---------|----------|---------|---------|-------------------

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM