javascript - 如何使用 document.getElementById 和 getElementsByClassName 做 Jasmine 测试用例以显示无 css 属性

标签 javascript css jasmine karma-jasmine

我是 jasmine 测试用例的新手 我尝试在执行此样式属性未定义后为选择模块做 jasmine 测试用例

 function Selection() {

    }
    Selection.prototype.expandFlightDetails = function() {

        document.getElementsByClassName("flight-details-container").style.display = 'none';
        document.getElementById("expandedFlightDetails").style.display = 'block';
    };
    Selection.prototype.hideFlightDetails = function() {
        document.getElementById("expandedFlightDetails").style.display = 'none';
        document.getElementsByClassName("flight-details-container").style.display = 'block';

    };

我的测试用例是

describe("selection module", function() {
    var selection;

    beforeEach(function () {
        selection= new Selection();

    });
    afterEach(function () {

    });
    it('expand the flight details part ' , function(){
        selection.expandFlightDetails();
        expect(document.body.getElementsByClassName('flight-details-container')[0].style.display).toEqual('none');

    });
    xit('hide the flight details part ', function(){
        selection.hideFlightDetails();
        expect(document.getElementById('expandedFlightDetails').style.display).toEqual('none');

    });
});

完成此操作后,我获取并删除了 beforEach 的代码

TypeError: Cannot read property 'style' of undefined

如果我做错了请指正

最佳答案

您在此代码上有一些错误。

首先在 Selection.prototype.expandFlightDetails 中确保获取数组的第一个结果(你忘记了 [0]):

document.getElementsByClassName("flight-details-container")[0]

Selection.prototype.hideFlightDetails 的相同评论

然后在您的测试套件中,您创建了一个名为 selection 的 Selection 实例,但在这两个测试中,您都使用了一个名为 flightselection 的变量,该变量未在任何地方声明。不应该是 selection 吗?

最后,您的问题似乎是您尝试在测试中操纵 'flight-details-container',尽管此元素是在 afterEach 回调中创建的。 afterEach 表示每次测试后都会执行,所以在测试期间不存在。

关于javascript - 如何使用 document.getElementById 和 getElementsByClassName 做 Jasmine 测试用例以显示无 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568322/

相关文章:

javascript - jquery 动画和 Internet Explorer 8 的问题

javascript - 砌体不适用于动态内容

css - 带有 tailwindcss 的特殊网格布局

css - 设置div和浏览器边框之间的距离?

css - 为什么当我切换到亚洲语言时,西里尔字母和希腊字母之间有多余的空格?

javascript - 自定义 Jasmine 匹配器和 promise

javascript - 脚本(AJAX 或 JS)在 IE8 中无法正常工作

javascript - 最小化 JS getter/setter 样板文件

reactjs - 找不到@typescript-eslint/no-unused-expressions'

javascript - 如何使用浅渲染而不是使用 NO_ERRORS_SCHEMA 编写 Angular Jasmine 简单的 'should create' 测试用例