2017-02-01 2 views
1

У меня есть функция в моем проекте «Реформирование», которая обрабатывает запрос HTTP GET. После некоторой обработки он использует Sequelize, чтобы найти пользовательский объект для моего текущего сеанса. User.findOne функция возвращает обещание и в зависимости от результата этого обещания, я посылаю ответ HTTP с 200 или 404.Как я могу проверить свой асинхронный код в обновлении HTTP-обработчика?

static getMe(req, res, next) { 
    const userInfo = BaseController.getUserSession(req); 

    // hard to test this part 
    User.findOne({ 
     where: {email: userInfo.email} 
    }).then(function(user) { 
     if (user) BaseController.respondWith200(res, user); 
     else BaseController.respondWith404(res, 'User not found.'); 
    }, function(error) { 
     BaseController.respondWith404(res, error); 
    }).then(function() { 
     return next(); 
    }); 
} 

Я попытался несколько различных библиотек, чтобы помочь с тестированием, так что я извините, если это беспорядочное сочетание вещей. Это в моей beforeEach функции для моих тестов:

const usersFixture = [ 
    {id:2, email:'[email protected]', facebookId:54321, displayName: 'Ozzy Osbourne'}, 
    {id:3, email:'[email protected]', facebookId:34521, displayName: 'Zakk Wylde'}, 
    {id:4, email:'[email protected]', facebookId:12453, displayName: 'John Lennon'} 
]; 

this.findOneSpy = sinon.spy(function(queryObj) { 
    return new Promise(function(resolve, reject) { 
    const user = usersFixture.find(function(el) { return el.email === queryObj.where.email }); 
    if (user) resolve(user); 
    else resolve(null); 
    }); 
}); 

this.respondWith200Spy = sinon.spy(function(res, data) {}); 
this.respondWith400Spy = sinon.spy(function(res, error) {}); 
this.respondWith404Spy = sinon.spy(function(res, error) {}); 

this.controller = proxyquire('../../controllers/user-controller', { 
    '../models/user': { 
    findOne: this.findOneSpy 
    }, 
    './base-controller': { 
    respondWith200: this.respondWith200Spy, 
    respondWith400: this.respondWith400Spy, 
    respondWith404: this.respondWith404Spy 
    } 
}); 

А вот что один из моих тестов выглядит следующим образом:

it('should return 200 with user data if user email matches existing user', function() { 
    // THIS FUNCTION IS NEVER HIT 
    this.respondWith200Spy = function(res, data) { 
    data.should.equal({id:4, email:'[email protected]', facebookId:12453, displayName: 'John Lennon'}); 
    done(); 
    }; 
    const req = {session:{user:{email:'[email protected]'}}}; 
    this.controller.getMe(req, this.res, this.nextSpy); 
    this.findOneSpy.should.have.been.called; 
}); 

Поскольку мы на самом деле не проходит обратный вызов функции и функции на самом деле ничего не возвращает (просто делает асинхронные вещи в другом месте), я не могу понять, как проверить его, чтобы убедиться, что он работает правильно. Любая помощь приветствуется.

Фактический код работает просто отлично. Я просто пытаюсь получить качественное модульное тестирование в проекте. Благодаря!

ответ

0

В итоге я нашел способ сделать это, используя proxyquire. Я только что повторно запустил класс контроллера, который я тестирую, и сделал обратный вызов respondWith200 сделать утверждение. Затем я создал новый шпион для функции next, которая просто вызывает done (который передается в тестовый пример). Я подтвердил, что код все попал.

it('should return 200 with user data if user email matches existing user', function(done) { 
    const controller = proxyquire('../../controllers/user-controller', { 
    '../models/user': { 
     findOne: this.findOneSpy 
    }, 
    './base-controller': { 
     respondWith200: function(res, data) { 
     data.displayName.should.equal('John Lennon'); 
     }, 
     respondWith400: this.respondWith400Spy, 
     respondWith404: this.respondWith404Spy 
    } 
    }); 
    const req = {grft_session:{user:{email:'[email protected]'}}}; 
    const nextSpy = sinon.spy(function() { 
    done(); 
    }); 
    controller.getMe(req, this.res, nextSpy); 
    this.findOneSpy.should.have.been.called; 
}); 
Смежные вопросы