eugef / node-mocks-http

Mock 'http' objects for testing Express routing functions
Other
755 stars 134 forks source link

Unable to get any response using response._getData() #149

Closed brijeshprasad89 closed 4 years ago

brijeshprasad89 commented 6 years ago

I have written the following code to fetch data from mondo db: Route:

router.get('/config/:id?', (req, res) => {
    return controller.findDataById(req, res);
});

controller: mongoClient.findDataById(params, res);

client:

DataModel.find({_id: params.id}).limit(1).
    then((data) => {
            return response.json(data);
    })
    .catch((err) => {
        logger.error('Error when retrieving data with id %s', params.id, err);
    });

I am trying to write the integration test for the same:

const httpMocks = require('node-mocks-http');

let request  = httpMocks.createRequest({
                method: 'GET',
        url: '/config/59cf3c6df36d286c005cc2a8',
        params: {
          id: '59cf3c6df36d286c005cc2a8'
        }
    });

    let response = httpMocks.createResponse();
    mongoClient.findDataById(request,response);
    let data =  response._getData();

I get nothing in data. Is there anything that I am doing wrong?

AlexChalk commented 6 years ago

I think _getData() is an async operation—I had this issue and resolved it by wrapping the call in a timeout. I admit it's not the best solution though.

If _getData() is async, it would be nice if it returned a Promise.

hephzaron commented 6 years ago

https://github.com/howardabrams/node-mocks-http/issues/73 check this out, it works for me

belyas commented 5 years ago

I have got almost same issue, here's my code:

import { CategoryRouter } from '../../../routes/web';
import httpMocks from 'node-mocks-http';

function buildResponse () {
    return httpMocks.createResponse();
}
describe('Category router', () => {
    it('Returns 200 status code', () => {
        const response = buildResponse()
        const request  = httpMocks.createRequest({
            method: 'GET',
            url: '/categories/',
        });

        CategoryRouter(request, response)

        console.log('[Res:data]', response._getData());
    });
});

It's a simple get router with sychronous code, no apis.

I get this error: TypeError: Cannot read property 'apply' of undefined

Anyone can help please?

Thanks in advance

github-actions[bot] commented 4 years ago

Stale issue message