как переставить или сменить реальный модуль http на ответный вызов? - PullRequest
0 голосов
/ 30 августа 2018

*************************** api / index.js *************** *************

 exports.search = function (req, res) {
    const requestObj = {
                 //Dummy Payload
               };
    const data = '432';
    request({
        url: 'config.url,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        json: true,
        body: requestObj
    }, (error, response) => {
        if (error) {
            return res.status(error.statusCode).json(error);
        }
        console.log('data', data);
        return res.status(response.statusCode).json(response.body);
    });
};

*************************** api / index.js *************** *************

*************************** test / index.js *************** *************

// unit tests
    const chai = require('chai');
    const sinon = require('sinon');
    const httpMocks = require('node-mocks-http');
    const rewire = require('rewire');
    const logger = require('../../../log/winston');
    const axios = require('axios');

    const expect = chai.expect;

    const search = rewire('../../api/index');
    const loadMethod = search.__set__('search');


function verifySearch(products, expectedHit) {
    expect(products.item.name).to.equal(expectedHit.item.name);
}

describe('Search Module Route Unit Tests', () => {
    describe('get product based  on search keywords routehandler', () => {
        let sandbox;
        beforeEach(() => {
            sandbox = sinon.sandbox.create();
        });

        afterEach(() => {
            sandbox.restore();
        });

        it('should call the search with search keywords', (done) => {
            const axiosSpy = sandbox.stub(axios, 'post').returns(Promise.resolve({ data: fakeResponse }));
            // setTimeout(done, 300);

            const request = httpMocks.createRequest({
                method: 'POST',
                url: '/api/v1/search',
                body: {
                    Keywords: ['blue']

                }
            });

            const response = httpMocks.createResponse({
                eventEmitter: require('events').EventEmitter
            });

            loadMethod(request, response);
             response.on('end', () => {
                const responseData = JSON.parse(response._getData());
                   verifySearch(responseData, fakeResponse);
                done();
            });
            expect(axiosSpy.calledOnce).to.equal(false);
        });
    });
});

*************************** test / index.js *************** *************

const fakeResponse = {
       "item":{
               "name":"Detole"
            }

}

**

Мне нужно совершать звонки в реальный модуль, но фактический звонок проверяется, но ответ я хочу установить фиктивный ответ.

**

...