Dale de Silva
Dale de Silva

Reputation: 116

How to test an HTML attr doesn't exist in jest & enzyme?

I'm trying to write a test to make sure a particular attribute doesn't exist in my output html, however, I'm having trouble figuring out the appropriate way. I'm using Jest and Enzyme.

The example html that's being tested is...

<a href="https://material.io/components/buttons" target="test" class="makeStyles-link-37 makeStyles-link-135">Material Design</a>

and the lines that do the testing are...

const linkProps = component.find('a').first().props();
expect( linkProps ).not.toHaveProperty('rel');

I'm not sure if the first line is the most efficient way to find the tag, but it's confirmed to be working. The second line, however, fails even though the rel attr doesn't exist in the html.

It fails with...

expect(received).not.toHaveProperty(path)
Expected path: not "rel"
Received value: undefined

When I use toHaveProperty to test that an attribute does exist, it's fine, but what's the appropriate way to test that it doesn't exist?

Upvotes: 0

Views: 1661

Answers (2)

AdriSolid
AdriSolid

Reputation: 2825

If your test title is 'attribute "rel" should not exist', I would follow same instructions in your test, like:

test('attribute "rel" should not exist', () => {
  const linkTag = component.find('a');
  expect(linkTag).not.toHaveAttribute('rel');
});

Check toHaveAttribute docs here!

Upvotes: 3

Dale de Silva
Dale de Silva

Reputation: 116

I've realised that one possible answer is to use prop() and toBe() If i'm expecting the attribute to undefined, then that's what I put into the toBe function.

const linkTag = component.find('a');
expect( linkTag.prop('rel') ).toBe(undefined);

There might be better answers though, so I'm not marking this one as correct just yet.

Upvotes: 1

Related Questions