【问题标题】:Custom jasmine matchers and protractor定制茉莉花火柴和量角器
【发布时间】:2015-07-28 18:03:12
【问题描述】:

我们添加了一个toHaveClass 自定义茉莉花匹配器,为了使其工作,我们必须将它添加到beforeEach()(在this topic 的帮助下)。

并且,为了遵循 DRY 原则并避免在需要 toHaveClass 的规范中在每个 beforeEach() 中重复匹配器定义,我们在 onPrepare() 中添加了一个 beforeEach() 块:

onPrepare: function () {
    var jasmineReporters = require("jasmine-reporters");
    require("jasmine-expect");

    // ...

    // custom matchers
    beforeEach(function() {
        jasmine.addMatchers({
            toHaveClass: function() {
                return {
                    compare: function(actual, expected) {
                        return {
                            pass: actual.getAttribute("class").then(function(classes) {
                                return classes.split(" ").indexOf(expected) !== -1;
                            })
                        };
                    }
                };
            }
        });
    });
},

它确实有效,但是每次我在量角器配置中看到beforeEach() 块时,我都会有一种微压抑和强烈的感觉,这不是定义匹配器的好地方。

问题:

有没有更好的方法或地方来定义自定义匹配器?

【问题讨论】:

    标签: javascript angularjs testing jasmine protractor


    【解决方案1】:

    我看到的最简单的解决方案是将这个 beforeEach 块移动到一个单独的文件中,并在 onPrepare 中要求它,就像你对供应商库所做的那样:

    onPrepare: function () {
        var jasmineReporters = require("jasmine-reporters");
        require("jasmine-expect");
        require('./tests/support/jasmine-custom-matchers'); // inject custom matchers
        // ....
    }
    

    beforeEach 的代码不需要任何更改:

    // /tests/support/jasmine-custom-matchers.js
    
    beforeEach(function() {
        jasmine.addMatchers({
            toHaveClass: function() {
                return {
                    compare: function(actual, expected) {
                        return {
                            pass: actual.getAttribute("class").then(function(classes) {
                                return classes.split(" ").indexOf(expected) !== -1;
                            })
                        };
                    }
                };
            }
        });
    });
    

    我认为你不应该从这个文件中export 一些东西,只要require-ing 它就会生效。

    【讨论】:

    • 这帮助我将额外的“jasmine-expect”匹配器添加到量角器!只需像您一样添加require("jasmine-expect");,然后将类型从“npm i -D @types/jasmine-expect”添加到tsconfig.json "types":["jasmine", "node", "jasmine-expect"]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多