can
can

Reputation: 214

How to set a function in Jasmine?

I'm trying to cover a function in Jasmine, but get an error 'TypeError: inputField.setAttribute is not a function'. What do I need to fix this? Need I mock this? Struggling a few days to fix this, but didn't get any solution.

Anyone who knows what I need to do?

The function:

setInput() {
    const inputField = this.$document[0].querySelector('.input-field');

    if (this.inputElement.styles.includes('InputYes')) {
        inputField.setAttribute('input-yes', '');
    } if (this.inputElement.styles.includes('InputNo')) {
        inputField.setAttribute('input-no', '');
    }
}

Jasmine:

describe('setInput method', () => {
    it('test', () => {
        // given
        var spy = spyOn(document, 'querySelector').and.returnValue(angular.element('<input class="input-field" type="text">'));
        const inputController = new InputController(this.$document);
        inputController.inputElement = {
            styles: ['InputYes']
        };

        // when
        inputController.setInput();

        // then
        expect(inputController.$document[0].querySelector('.input-field')[0].getAttribute('input-yes')).toBe('');
        expect(spy).toHaveBeenCalledWith('<input class="input-field" input-yes type="text">');
    });
});

Upvotes: 0

Views: 580

Answers (1)

JeffryHouser
JeffryHouser

Reputation: 39408

I'm guessing but based on a quick code review. Your code is accessing $document as an array:

this.$document[0].querySelector('.input-field');

But, your spy is just on document:

 var spy = spyOn(document, 'querySelector').and.returnValue(angular.element('<input class="input-field" type="text">'));

Based on the code you shared, I'd guess that $document[0] is not the same as document

I postulate if you spy on the $document object in the component you may get better results. Like this:

var spy = spyOn(inputController.$document[0], 'querySelector').and.returnValue(angular.element('<input class="input-field" type="text">'));

Upvotes: 1

Related Questions