如何为该方法编写单元测试?
import { CoreOptions, UriOptions } from 'request';
import requestPromise from 'request-promise-native';
export class Client {
public async post(request: CoreOptions & UriOptions) {
return requestPromise.post(request)
}
}
我的单元测试代码出现错误。(请求错误:错误:connect ECONNREFUSED 127.0.0.1:3000(。如何解决?
import { Client } from '../source/http/Client';
import { expect } from 'chai';
import requestPromise from 'request-promise-native';
import sinon from 'sinon';
describe('Client', () => {
afterEach(() => {
sinon.restore();
});
it('should pass', async () => {
const client = new Client();
const response = {};
const postStub = sinon.stub(requestPromise, 'post').resolves(mResponse);
const actual = await client.post({ uri: 'http://localhost:3000/api', method: 'POST' });
expect(actual).to.be.equal(response);
sinon.assert.calledWithExactly(postStub, { uri: 'http://localhost:3000/api', method: 'POST' });
});
});
我的代码中有什么不正确的地方?我不明白。
您可以使用sinon.stub
为requestPromise.post
方法制作存根。例如
client.ts
:
import { CoreOptions, UriOptions } from 'request';
import requestPromise from 'request-promise-native';
export class Client {
public async post(request: CoreOptions & UriOptions) {
return requestPromise.post(request);
}
}
client.test.ts
:
import { Client } from './client';
import { expect } from 'chai';
import requestPromise from 'request-promise-native';
import sinon from 'sinon';
describe('61384662', () => {
afterEach(() => {
sinon.restore();
});
it('should pass', async () => {
const client = new Client();
const mResponse = {};
const postStub = sinon.stub(requestPromise, 'post').resolves(mResponse);
const actual = await client.post({ uri: 'http://localhost:3000/api', method: 'GET' });
expect(actual).to.be.equal(mResponse);
sinon.assert.calledWithExactly(postStub, { uri: 'http://localhost:3000/api', method: 'GET' });
});
});
100%覆盖率的单元测试结果:
61384662
✓ should pass
1 passing (262ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
client.ts | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
源代码:https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61384662