Skip to content

Commit

Permalink
feat: pass item index into callback (#126)
Browse files Browse the repository at this point in the history
* feat: pass the item index into the callback

* update readme
  • Loading branch information
bahmutov authored Feb 16, 2024
1 parent f0d9110 commit 27fdaad
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 31 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ it.each(selectors)('element %s is visible', (selector) => {
// "element .new-todo is visible"
```

## item index

In addition to the item, the callback receives the index

```js
it.each(selectors)('element %s is visible', (selector, k) => {
// k is 0, 1, 2, ...
})
```

## Multiple arguments

You can pass multiple arguments into the callback function by using an array of arrays. For example, to check if an element is visible, invisible, or exists, you can have both a selector and the assertion string for each item.
Expand Down
13 changes: 13 additions & 0 deletions cypress/e2e/passes-index.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// @ts-check
/// <reference types="cypress" />

import '../..'

describe('passes index', () => {
const items = ['foo', 'bar', 'baz']

it.each(items)('index %K', (item, k) => {
expect(k, `index ${k}`).to.be.within(0, items.length - 1)
expect(item, `item ${item}`).to.equal(items[k])
})
})
35 changes: 6 additions & 29 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,11 @@ if (!it.each) {
// define a test for each value
if (Array.isArray(value)) {
it(title, function itArrayCallback() {
return testCallback.apply(this, value)
return testCallback.apply(this, value, k)
})
} else {
it(title, function itCallback() {
return testCallback.call(this, value)
return testCallback.call(this, value, k)
})
}
}, this)
Expand Down

0 comments on commit 27fdaad

Please sign in to comment.