Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does expect in chai work with a text string?

I am trying to understand expect behaviour in chai.js. I have the code to check if the login fails with invalid credentials. This is my code:

describe('Login', function() {
  before(function(done) {
    driver.get('https://pluma-dev.herokuapp.com/client-sign-in').then(done);
  });
  it('Login with Incorrect credentials', function( done ) {
driver.findElement(webdriver.By.name("username")).sendKeys("[email protected]");
      driver.findElement(webdriver.By.name("password")).sendKeys("123"); 
      driver.findElement(webdriver.By.className("client-onboarding-signin-btn")).click().then(function(){
      driver.findElement(By.css(".has-error")).getText().then(function (text) {
        console.log(text);
        try{
                expect(text).to.be.a("Invalid email or password");
                done();
        } catch (e) {
                done(e);
        }

      });

});

    });

});

according to my understanding this test case should pass because i am expecting invalid username and password and got the same. However, it throws an Assertion error. That is, 1) Login Login with Incorrect credentials: AssertionError: expected 'Invalid email or password' to be an invalid email or password

like image 429
user2987322 Avatar asked Dec 07 '16 07:12

user2987322


People also ask

How does Chai should work?

The should interface supports the same chaining interface as expect() . The key difference is that Chai adds a should() function to every JavaScript value. That means you don't have to call expect() explicitly, which makes assertions read more like natural language. require('chai').

Do you need assertion in Chai?

The should style allows for the same chainable assertions as the expect interface, however it extends each object with a should property to start your chain. This style has some issues when used with Internet Explorer, so be aware of browser compatibility.

What assertion styles are present in Chai testing assertion library?

Chai is such an assertion library, which provides certain interfaces to implement assertions for any JavaScript-based framework. Chai's interfaces are broadly classified into two: TDD styles and BDD styles.


1 Answers

You are using the wrong assertion. You want to use:

expect(text).to.equal("Invalid email or password");

.to.be.a (which really is just a call to the assertion named a) asserts that the value has a certain type. Here is some code illustrating the difference:

const expect = require("chai").expect;

it("a", () => expect("foo").to.be.a("foo"));
it("equal", () => expect("foo").to.equal("foo"));
it("correct use of a", () => expect("foo").to.be.a("string"));

The first test will fail. The 2nd and 3rd are correct usages, so they pass.

You can find the documentation for a here.

like image 124
Louis Avatar answered Nov 15 '22 17:11

Louis