Вы можете использовать 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