-1

How can I write a unit test for this method?

import { CoreOptions, UriOptions } from 'request';
import requestPromise from 'request-promise-native';

export class Client {

    public async post(request: CoreOptions & UriOptions) {
        return requestPromise.post(request)
    }  
}

I get an error with my unit test code. (RequestError: Error: connect ECONNREFUSED 127.0.0.1:3000). How can I resolve it?

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' });
  });
});

What's incorrect in my code? I don't understand it.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Darkin Rall
  • 377
  • 1
  • 4
  • 17

1 Answers1

0

You can use sinon.stub to make a stub for requestPromise.post method. E.g.

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' });
  });
});

unit test results with 100% coverage:

  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 |                   
-----------|---------|----------|---------|---------|-------------------

source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61384662

Lin Du
  • 88,126
  • 95
  • 281
  • 483