Check if element has class only with Jasmine test framework

11,003

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;
                        })
                    };
                }
            };
        },
    });
});
Share:
11,003
d_z90
Author by

d_z90

Just a simple wannabe front-end developer.

Updated on August 08, 2022

Comments

  • d_z90
    d_z90 almost 2 years

    I am using webdriverJS and Jasmine to perform an end-to-end testing of a web page. I would like to test if an element has class under certain circumstances, but I would like to do it using methods from pure jasmine.

    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
    d_z90 almost 9 years
    Hey 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 pure javascript, jasmine syntax?
  • alecxe
    alecxe almost 9 years
    @d_z90 okay, makes sense. I've added the matcher we are currently using. Hope that helps.
  • d_z90
    d_z90 almost 9 years
    It'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.