Check if element has class only with Jasmine test framework
If you don't want having jasmine-jquery
or other third-party packages introducing custom jasmine matchers as a dependency, you can always extract the toHaveClass()
matcher implementation and use it. Note that having your assertion logic encapsulated inside custom matchers helps to follow the DRY principle and make your tests cleaner.
FYI, here is toHaveClass
implementation we are currently using:
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;
})
};
}
};
},
});
});
![d_z90](https://i.stack.imgur.com/z0FMn.jpg?s=256&g=1)
Comments
-
d_z90 almost 2 years
I am using
webdriverJS
andJasmine
to perform an end-to-end testing of a web page. I would like to test if an element hasclass
under certain circumstances, but I would like to do it using methods from purejasmine
.This is the part of the code where the issue is located:
describe('Header bar', function() { it('should show/hide elements accoding to the window position', function() { this.driver.executeScript('scroll(0, 1000)'); var elemSearch = this.driver.findElements(webdriver.By.id('animatedElement, animatedElement2, animatedElement3')); expect(elemSearch).toContain('appear-2'); }); })
Do you know if there's a way to solve this issue, or a couple of examples I could look at, without using extensions like
jasmine-jquery
?Thanks in advance for your replies!
-
d_z90 almost 9 yearsHey man! Actually I still have a question concerning this issue: the method I used doesn't work properly and the version you linked me uses
jquery
. Is there a way to code the custom matcher in purejavascript
,jasmine
syntax? -
alecxe almost 9 years@d_z90 okay, makes sense. I've added the matcher we are currently using. Hope that helps.
-
d_z90 almost 9 yearsIt's the same code I have used and it appears right, but I have two problems: no matter the name of the class, it passes the test. Instead if I use
.not.toHaveClass
it crashes. I have posted a [question] stackoverflow.com/questions/32715770/… about this issue, to show you exactly what I mean.