Jasmine tests check if html contains text and return boolean

47,230

Solution 1

From the Jasmine docs:

The 'toContain' matcher is for finding an item in an Array

You are trying to find a string inside a string so I would do something like this:

expect(view.$el.html().indexOf('Admin') !== -1).toBe(true);

Solution 2

toContain() now can actually be used for substring in string checks:

expect(view.$el.html()).toContain('Admin');
Share:
47,230
Spdexter
Author by

Spdexter

Updated on September 20, 2020

Comments

  • Spdexter
    Spdexter over 3 years
    expect(view.$el.html()).toContain('Admin');
    

    The view does contain the word 'Admin' so I was expecting it to return true. How can I achieve this?

    expect(view.$el.html()).toContain('Admin');
    

    This returns undefined. How can I make it return true?

    <header class="main">
      <div id="heading">
        <ul class="header-view right">
          <li class="inline"><a href="#link" class="button help-btn tab-btn"><span>  </span>Help</a></li>
          <li class="inline last"><a href="#og" class="button admin-btn tab-btn expand-admin"><span></span>Admin</a></li>
        </ul>
      </div>
    </header>
    

    This is what is returned from view.$el.html

    Please help.

  • Tomás Fox
    Tomás Fox over 8 years
    toMatch can also be used: expect(view.$el.html()).toMatch('Admin'). The toMatch matcher is for regular expressions.
  • hakunin
    hakunin over 7 years
    Please update the answer as this is both a bad way of solving it and outdated.
  • Aniruddha Das
    Aniruddha Das about 6 years
    Somehow this is not working for me error ===> ✗ change version: BData details page - Expected 'xxx/data-objects/NS_PROTRACTOR_TEST_DL42/DATA_LINEAGE_TEST/‌​PRC/…' to match '/data-objects/NS_PROTRACTOR_TEST_DL42/DATA_LINEAGE_TEST/PRC‌​/ORC/0/versionTest/0‌​;'. I am using contain to check substring
  • Wagner Danda da Silva Filho
    Wagner Danda da Silva Filho over 5 years
    Actually, it does work - I was just doing the check against the nativeElement instead of the actual text. My bad!
  • Ambroise Rabier
    Ambroise Rabier about 5 years
    const content: HTMLElement = fixture.debugElement.nativeElement; expect(content.innerHTML).toContain('Admin'); for those looking for equivalent on angular 2.