How to perform assertion for all nodes of a selector?

1.2k views Asked by At

In my testcafe test, I have a selector that matches multiple nodes. I want to execute an assertion on all nodes that are matched by this selector.

This will perform the assertion only on the first element returned by mySelector

await t.expect(mySelector.innerText).eql("foo");

This will perform it on all elements, but it is really verbose:

const count= await mySelector.count;
for (let i = 0; i < count; ++i) {
    await t.expect(mySelector.nth(i).innerText).eql("foo");
}

Is there a built-in way to do this that I am missing?

2

There are 2 answers

3
Alexander Moskovkin On BEST ANSWER

TestCafe doesn't have methods like expectEach so I think the way you propose is the best one. It adds a few lines of code but it makes it clear what you want to check in your test.

0
Zachary Ryan Smith On

As answered by @Alexander Moskovkin, "TestCafe doesn't have methods like expectEach...". However, I decided to make expectEach in my testcafe-utils module. As shown in the example usage below, I recommend interpolating eachAsync's @n param in the @message param of assertions so that on test failures you know which n-th element caused the failure.

const { Selector } = require('testcafe');
const tu = require('testcafe-utils');

const baseURL = 'http://www.imdb.com/title/tt0092400/ratings?ref_=tt_ov_rt';

fixture `IMDB`
  .page `${baseURL}`;

const mySelector = Selector('#main .title-ratings-sub-page table:nth-of-type(2) tr');

test('it', async t => {
  await tu.expectEach(mySelector, n => t.expect(mySelector.nth(n).innerText).match(/all/gi, `Failed on n '${n}'.`));
})