not.custom_matcher error - Jasmine

旧时模样 提交于 2019-12-10 11:16:40

问题


I have created a custom matcher in jasmine to verify if an element has a class or not. This is the code that I have placed in the beforeEach() function to define the custom matcher:

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

    this.driver = new webdriver.Builder().forBrowser('firefox').build();
    this.driver.manage().window().maximize();
    this.driver.get('http://localhost:8000/');
});

Then in the it function toHaveClass works properly, but when I combine it with the .not method, I get a really weird mistake. This is the part of the code where I am having the error:

it('should not create conflicts between the headers', function() { 
    this.driver.manage().window().setSize(767, 632);
    this.driver.findElement(webdriver.By.className('navbar-toggle')).click();
    var headerBar = this.driver.findElement(webdriver.By.className('navbar-collapse'));
    this.driver.manage().window().setSize(1000, 632).then(function() {
        expect(headerBar).not.toHaveClass('in');      
    });
});

Do you know what could be the issue that causes the test to crash? Thanks in advance for your replies!


回答1:


To me it looks like your actual ends undefined or null, because you avoid to return -1.

With the line return classes.split(' ').indexOf(expected) !== -1; you only return on found values, so not found values get not returned.

One experimental thing you could try is to remove the condition !== -1, so also a not found gets returned. However, I don't know the side impacts of this; it could break just at another part or (as .not is looking for some kind of false-return), it still might not work and even your positive cases with expect().toHaveClass() could end successful when they should fail.

The safer option I see is to create another custom matcher toNotHaveClass and then return only on === -1, so only if a value isn't found. Basically this:

jasmine.addMatchers({
    toNotHaveClass: function() {
        return {
            compare: function(actual, expected) {
                return {
                    pass: actual.getAttribute('class').then(function(classes) {
                        return classes.split(' ').indexOf(expected) === -1;
                    })
                }
            }
        }
    }
});


来源:https://stackoverflow.com/questions/32715770/not-custom-matcher-error-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!