[英]How to mock a standalone imported function with sinon
How can I mock this axios import with sinon and then use expectations ?我怎样才能用 sinon 模拟这个 axios 导入,然后使用期望? I have tried:我试过了:
import axios from 'axios';
axiosMock = sinon.mock(axios);
but the expectation fails :但期望失败:
describe('Random test', () => {
it('should run the test', async () => {
axiosMock.withArgs(sinon.match.any).once();
await getName();
}
}
The function under test is :被测函数为:
import axios, { AxiosRequestConfig } from 'axios';
async function getName() {
const config: AxiosRequestConfig = {
method: 'GET',
url: ' someUrl',
headers: {},
};
const res = await axios(config);
return res;
}
Sinon doesn't support stub standalone function imported from a module. Sinon 不支持从模块导入的存根独立函数。 A solution is to use link-seams .一种解决方案是使用link-seams 。 Therefore, we need to use proxyquire to construct the seams.因此,我们需要使用proxyquire来构造接缝。
Eg例如
getName.ts
: 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
: 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: {},
});
});
});
test result:测试结果:
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.