【问题标题】:How to set a function in Jasmine?如何在 Jasmine 中设置功能?
【发布时间】:2023-03-22 20:15:01
【问题描述】:

我试图覆盖 Jasmine 中的一个函数,但得到一个错误“TypeError: inputField.setAttribute is not a 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', '');
    }
}

茉莉花:

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">');
    });
});

【问题讨论】:

    标签: javascript angular unit-testing jasmine typeerror


    【解决方案1】:

    我猜是基于快速代码审查。您的代码正在以数组的形式访问 $document

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

    但是,你的间谍只是在文件上:

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

    根据您分享的代码,我猜$document[0]document 不一样

    我假设如果你监视组件中的$document 对象,你可能会得到更好的结果。像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2019-09-10
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 2020-07-30
      相关资源
      最近更新 更多