我如何为这个方法写一个单元测试?
import { CoreOptions, UriOptions } from 'request';
import requestPromise from 'request-promise-native';
export class Client {
public async post(request: CoreOptions & UriOptions) {
return requestPromise.post(request)
}
}
我的单元测试代码出现了错误。(RequestError.错误:连接ECONNREFUSED 127.0.0.1:3000 错误:连接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.commrdulinexpressjs-researchtreemastersrcstackoverflow61384662。