Search code examples
reactjsjasminetddjestjsenzyme

Expect toContain text from a set of values in jest,enzyme with React


My below test works,

let output = mount(story);
      expect(output.text()).toContain('Superman');

But I need to even alllow Batman and Spiderman to pass: I need to check if output.text() has either -> ['Superman','Batman','Spiderman']

Can't do it with

expect(output.text()).toContain(['Superman','Batman','Spiderman']);

output.text() willl contain "Superman is the best" or "Spiderman is the best"


Solution

  • You can add your own matcher instead of toContain.

    expect.extend({
      toContainHero(text) {
        let pass = false;
        const heroes = ['Superman','Batman','Spiderman'];
        heroes.forEach((hero) => {
          pass = text.indexOf(hero) !== -1;
        })
        if (pass) {
          return {
            message: () =>
              `expected hero to be found`,
            pass: true,
          };
        } else {
          return {
            message: () => `expected hero to be not found`,
            pass: false,
          };
        }
      },
    });
    

    And then do:

    expect(output.text()).toContainHero();