Как проверить события, сгенерированные из http-запроса node.js?

У меня есть код 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 ответ

Решение

Вам просто нужно сделать свой собственный 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());
})

Другие вопросы по тегам