Как проверить события, сгенерированные из http-запроса node.js? - PullRequest
0 голосов
/ 12 июня 2018

У меня есть код node.js, который я тестирую с помощью mocha и sinon

var request = require('request');
request.get(url, function (error, response, body) {
  /* code I already tested */
})
.on('error', function(err) {
  /* code I want to test */
})

Я создал заглушку с помощью sinon var requestGet = sinon.stub(request, 'get'); и создал различные модули для тестирования /* code I already tested */

Теперь я хочу проверить код /* code I want to test */, выполняемый, когда request.get() генерирует событие error, но я не знаю, как это сделать.

1 Ответ

0 голосов
/ 12 июня 2018

Вам просто нужно сделать свой собственный EventEmitter, заглушить метод .get и использовать его по своему усмотрению.Вы сможете создавать любые события:

//Stubbing
emitter = new EventEmitter();
sandbox.stub(request, 'get').returns(emitter);

//And when you need to fire the event:
emitter.emit('error', new Error('critical error'));

Вот пример.

Скажем, у вас есть метод makeRequest.И вы хотите проверить, что в случае критической ошибки приложение должно быть остановлено путем вызова application.stop().

Вот как вы можете это проверить (см. Мои комментарии):

const request = require('request');
const sinon = require('sinon');
const assert = require('assert');
const { EventEmitter } = require('events');

const application = { stop () { console.log('appliation is stopped') } };

const makeRequest = () => {
    return request
        .get('http://google.com', function (error, response, body) {
            if (error) { return console.error(error); }

            console.log('executed');
        })
        .on('error', err => {
            if (err.message === 'critical error') {
                application.stop();
            }
        });
}

describe('makeRequest', () => {
    let emitter;

    let sandbox = sinon.createSandbox();
    let stopSpy;

    beforeEach(() => {
        // Using our own emitter. We'll be able to raise any events.
        emitter = new EventEmitter();

        // We don't want the standard `get` logic to be executed as we are testing the error only.
        // Notice - we are returning `emitter` so the .on method exists.
        sandbox.stub(request, 'get').returns(emitter);

        stopSpy = sandbox.spy(application, 'stop');
    });


    it('should stop the app in case of a critical error', () => {
        // No need to worry about the callbacks, the stubbed method is sync.
        makeRequest();

        // Now emitting the error.
        emitter.emit('error', new Error('critical error'));

        // Checking if the required method has been called.
        assert.equal(stopSpy.calledOnce, true);
    });

    afterEach(() => sandbox.restore());
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...