vendredi 29 septembre 2017

How to test internal promise in NodeJS

I am trying to test a service that is calling another service which I am trying to spy on and evaluate it has been called. The issue is the test assertion is wrapped in a promise which is resolved in the method and not returned as in most tutorials. When using

stubResponse.rejects(rejectionMessage)**()**.catch((err)

I can get the code to run but the callback in the test executes before the call to the actual method so it results in false but the test is still green ?!

When using stubResponse.rejects(rejectionMessage).catch((err) I get

TypeError: stubResponse.rejects(...).catch is not a function

My question resumes to how can I test a call to a stubbed/spied/mocked internal service call inside a promise that is never exposed ? This cannot be a rare use case but cannot find any relevant results.

Relevant code:

service.js

const httpService = require('./requestService');
const apiaiService = require('./apiaiService');

const processMessagePostback = function postBackMessage(event) {
  let senderIdPresent = typeof event !== 'undefined' && typeof event.sender !== 'undefined' && typeof event.sender.id !== 'undefined';
  let messagePresent = typeof event !== 'undefined' && typeof event.message !== 'undefined' && typeof event.message.text !== 'undefined';

  if(senderIdPresent && messagePresent) {
    let senderId = event.sender.id;
    let message = event.message.text;

    apiaiService.getApiAiResponse(senderId, message)
        .then((res) => {
            logger.debug('Sending conversational reply',{message: message,apiaiResponse: res});
            httpService.sendMessage(senderId, res);
        })
        .catch((err) => {
            logger.error('Api Ai error',{error: err});
        })
  } else {
    logInvalidEvent(event);
  }
};

service.spec.js

const expect = require('chai').expect;
const sinon = require('sinon');
const proxyquire = require('proxyquire');
const stubHttpService = {};
const sinonLoggerSpy = {};
const postbackService = proxyquire('./postbackService',{'./requestService':stubHttpService, './apiaiService': stubApiAi, '../utils/logger':sinonLoggerSpy});

....
    it('processMessagePostback should log error given api ai error',() => {
    event.sender = {id:0};
    event.message = {text:'TEST'};
    let rejectionMessage = "REJECTED_TEST";

    let stubResponse = sinon.stub();
    stubApiAi.getApiAiResponse = stubResponse;

    stubResponse.rejects(rejectionMessage)().catch((err) => {
        sinon.assert.calledOnce(sinonLoggerSpy.error);
    });

    postbackService.processMessagePostback(event);
});

Aucun commentaire:

Enregistrer un commentaire