Sinon: Stubbing статический метод класса не работает, как ожидалось - PullRequest
0 голосов
/ 14 октября 2018

Я хочу смоделировать следующий класс, который используется в качестве зависимости для другого:

module.exports = class ResponseHandler {

static response(res, status_, data_, codes_) {
    console.log('Im here. Unwillingly');
    // doing stuff here...
};

ResponseHandler импортируется ProfileController и используется там:

const response = require('../functions/tools/response.js').response;

module.exports = class ProfileController {

static async activateAccountByVerificationCode(req, res) {
    try{
        // doing stuff here
        return response(res, status.ERROR, null, errorCodes);
    }
}

СейчасЯ пишу модульные тесты для ProfileController и там я тестирую, если activAccountByVerificationCode вызывает ответ с заданными аргументами

describe('ProfileController', () => {

    let responseStub;

    beforeEach(function() {

        responseStub = sinon.stub(ResponseHandler, 'response').callsFake(() => null);
    });

Но несмотря на то, что ответ является поддельным, ProfileController по-прежнему вызывает реальную реализацию ответа (см. Вывод консоли: «Я здесь. Нежелательно» )

    it('should respond accordingly if real verification code does not fit with the one passed by the user', async function () {
        // here you can still see that real implementation is still called
        // because of console output 'I'm here unwillingly'
        await controller.activateAccountByVerificationCode(req, res);

        console.log(responseStub.called); // -> false
        expect(responseStub.calledWith(res, status.ERROR, null, [codes.INVALID_VERIFICATION_CODE])).to.eql(true); // -> negative
    });

1 Ответ

0 голосов
/ 15 октября 2018

Вам нужно сначала смоделировать зависимости контроллеров с помощью библиотеки, подобной proxyquire, а затем использовать этот проверенный экземпляр в своем тесте.В противном случае вы все равно будете использовать оригинальную (unstubbed) реализацию.

const proxyquire = require('proxyquire');

describe('ProfileController', () => {

    let responseStub;
    let Controller;

    beforeEach(function() {

        responseStub = sinon.stub(ResponseHandler, 'response').callsFake(() => null);
        Controller = proxyquire('./ProfileController', {'../functions/tools/response':responseStub})
    });

    it('should respond accordingly if real verification code does not fit with the one passed by the user', async function () {
        // here you can still see that real implementation is still called
        // because of console output 'I'm here unwillingly'
        await Controller.activateAccountByVerificationCode(req, res);

        console.log(responseStub.called); // -> false
        expect(responseStub.calledWith(res, status.ERROR, null, [codes.INVALID_VERIFICATION_CODE])).to.eql(true); // -> negative
    });

Controller, затем использует вашу версию с заглушкой и может быть проверена.

...