我正在测试软件,我想验证发送到API的请求是否具有正确的数据。此特定方法创建具有某些数据,标头等的请求,然后通过axios
将请求发送到外部API。示例代码:
myFunction() {
const data = {
example: 'my data'
};
const headers = {
'content-type': 'application/json'
}
const request = {
method: 'POST',
baseUrl: 'http://myawesome-site.com',
url: '/api/path',
headers,
data,
}
return axios(request)
.then(res => ...do something)
.catch(err => ...do something else)
}
[我想知道是否有一种方法可以使用chai
或sinon
来拦截axios调用并仅访问“请求”对象以仅验证正在发送的数据,我不在乎回应。
这里是单元测试解决方案,您应该使用sinon.stub
:
[当您要防止直接调用特定方法时(可能是因为它触发了不希望的行为,例如XMLHttpRequest或类似内容
例如index.ts
:
import axios, { AxiosRequestConfig } from 'axios';
exports.myFunction = function myFunction() {
const data = {
example: 'my data'
};
const headers = {
'content-type': 'application/json'
};
const request: AxiosRequestConfig = {
method: 'POST',
baseURL: 'http://myawesome-site.com',
url: '/api/path',
headers,
data
};
return exports
.axios(request)
.then(res => console.log('do something'))
.catch(err => console.log('do something else'));
};
exports.axios = axios;
index.spec.ts
:
const mod = require('./');
import sinon from 'sinon';
import { expect } from 'chai';
describe('myFunction', () => {
afterEach(() => {
sinon.restore();
});
it('should send request', async () => {
const mResponse = { status: 200 };
const axiosStub = sinon.stub(mod, 'axios').resolves(mResponse);
const logSpy = sinon.spy(console, 'log');
await mod.myFunction();
expect(
axiosStub.calledWith({
method: 'POST',
baseURL: 'http://myawesome-site.com',
url: '/api/path',
headers: {
'content-type': 'application/json'
},
data: {
example: 'my data'
}
})
).to.be.true;
expect(logSpy.calledWith('do something')).to.be.true;
});
it('should handle request error', async () => {
const mError = new Error('network error');
const axiosStub = sinon.stub(mod, 'axios').rejects(mError);
const logSpy = sinon.spy(console, 'log');
await mod.myFunction();
expect(
axiosStub.calledWith({
method: 'POST',
baseURL: 'http://myawesome-site.com',
url: '/api/path',
headers: {
'content-type': 'application/json'
},
data: {
example: 'my data'
}
})
).to.be.true;
expect(logSpy.calledWith('do something else')).to.be.true;
});
});
单元测试结果覆盖率100%:
myFunction
do something
✓ should send request
do something else
✓ should handle request error
2 passing (14ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57807855