问题
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