为了存根axios 函数,您需要一个名为proxyquire 的额外包。欲了解更多信息,请参阅How to use Link Seams with CommonJS
单元测试解决方案:
index.js:
const axios = require('axios');
const callValidateCookieApi = async (cookie) => {
try {
const config = {
method: 'post',
url: process.env.API_COOKIE_VALIDATION,
headers: {
Cookie: cookie,
},
};
return await axios(config);
} catch (error) {
console.log(error.message);
return error;
}
};
module.exports = { callValidateCookieApi };
index.test.js:
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const { expect } = require('chai');
describe('64374809', () => {
it('should pass', async () => {
const axiosStub = sinon.stub().resolves('fake data');
const { callValidateCookieApi } = proxyquire('./', {
axios: axiosStub,
});
const actual = await callValidateCookieApi('sessionId');
expect(actual).to.be.eql('fake data');
sinon.assert.calledWithExactly(axiosStub, {
method: 'post',
url: undefined,
headers: {
Cookie: 'sessionId',
},
});
});
it('should handle error', async () => {
const mErr = new Error('network');
const axiosStub = sinon.stub().rejects(mErr);
const { callValidateCookieApi } = proxyquire('./', {
axios: axiosStub,
});
const actual = await callValidateCookieApi('sessionId');
expect(actual).to.be.eql(mErr);
sinon.assert.calledWithExactly(axiosStub, {
method: 'post',
url: undefined,
headers: {
Cookie: 'sessionId',
},
});
});
});
单元测试结果:
64374809
✓ should pass (84ms)
network
✓ should handle error
2 passing (103ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------