Git Product home page Git Product logo

cypress-each's Introduction

cypress-each cypress version renovate-app badge ci

A demo of mocha-each and custom describe.each and it.each implementation for Cypress

๐ŸŽ“ Study the course Cypress Plugins

Blog posts

Videos

Install and use

# install using NPM
$ npm i -D cypress-each
# install using Yarn
# yarn add -D cypress-each

Import cypress-each in a single spec or in Cypress support file

import 'cypress-each'
// now can use describe.each and it.each

Let's create a separate test for each selector from a list

import 'cypress-each'

// create a separate test for each selector
const selectors = ['header', 'footer', '.new-todo']
it.each(selectors)('element %s is visible', (selector) => {
  cy.visit('/')
  cy.get(selector).should('be.visible')
})
// creates tests
// "element header is visible"
// "element footer is visible"
// "element .new-todo is visible"

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.

const data = [
  // each entry is an array [selector, assertion]
  ['header', 'be.visible'],
  ['footer', 'exist'],
  ['.new-todo', 'not.be.visible'],
]
it.each(data)('element %s should %s', (selector, assertion) => {
  cy.visit('/')
  cy.get(selector).should(assertion)
})
// creates tests
// "element header should be.visible"
// "element footer should exist"
// "element .new-todo should not.be.visible"

Repeat the test N times

You can use this module to simply repeat the test N times

// repeat the same test 5 times
it.each(5)('test %K of 5', function (k) {
  // note the iteration index k is passed to each test
  expect(k).to.be.within(0, 4)
})

// you can repeat the suite of tests
describe.each(3)('suite %K of 3', function (k) {
  ...
})

See the repeat-spec.js

Test and suite titles

You can use the arguments to the test callback in the test title in order.

it.each([10, 20, 30])('number is %d', (x) => { ... })
// creates the tests
// "number is 10"
// "number is 20"
// "number is 30"

You can also insert the arguments from the test callback via positions (0-based) into the title

const list = [
  ['foo', 'main'],
  ['bar', 'edge'],
]
it.each(list)('testing %1 value %0')
// "testing main value foo"
// "testing edge value bar"

If you want to use the iteration variable in the title, use %k for zero-based index, or %K for one-based index.

it.each([10, 20, 30])('checking item %k', (x) => { ... })
// creates the tests
// "checking item 0"
// "checking item 1"
// "checking item 2"
it.each([10, 20, 30])('checking item %K', (x) => { ... })
// creates the tests
// "checking item 1"
// "checking item 2"
// "checking item 3"

You can use %N to insert the total number of items

it.each(['first', 'second'])('test %K of %N', (x) => { ... })
// creates the tests
// "test 1 of 2"
// "test 2 of 2"

Example: it.each([10, 20, 30])('case %K: an item costs $%d.00 on sale', ...

Formatted test titles

Title function

You can form the test title yourself using a function. The function will get the item, the index, and all items and should return a string with the test title.

function makeTestTitle(s, k, strings) {
  return `test ${k + 1} for "${s}"`
}
it.each(['first', 'second'])(makeTestTitle, () => ...)
// creates the tests
// 'test 1 for "first"'
// 'test 2 for "second"'

It is very useful for forming a test title based on a property of an object, like

it.each([
  { name: 'Joe', age: 30 },
  { name: 'Mary', age: 20 },
])(
  (person) => `tests person ${person.name}`,
  (person) => { ... }
})
// creates the tests
// "tests person Joe"
// "tests person Mary"

See [cypress/integration/title-function.js](./cypress/integration/ title-function.js) for more examples

Every Nth item

You can quickly take every Nth item from an array

it.each(items, N)(...)

This is the same as taking the index of the item (zero-based) and doing k % N === 0

const items = [1, 2, 3, 4, 5, 6, ...]
it.each(items, 3)(...)
// tests item 1, 4, 7, ...

Chunking

There is a built-in chunking helper in describe.each and it.each to only take a subset of the items. For example, to split all items into 3 chunks, and take the middle one, use

it.each(items, 3, 1)(...)

The other spec files can take the other chunks. The index starts at 0, and should be less than the number of chunks.

// split all items among 3 specs
// spec-a.js
it.each(items, 3, 0)(...)
// spec-b.js
it.each(items, 3, 1)(...)
// spec-c.js
it.each(items, 3, 2)(...)

Sampling

Cypress bundles Lodash library which includes _.sampleSize method that you can use to randomly pick N items when passing the list to it.each

// pick 2 random items from the array and create 2 tests
it.each(Cypress._.sampleSize(items, 2))(...)

Custom filter predicate

You can filter the items by passing a predicate function

it.each(items, (x, k) => ...)
// creates a test for every item the predicate returns a truthy value

Return value

it.each(...)(...) and describe.each(...)(...) return the number of created tests.

const n = it.each([1, 2])(...)
// n is 2

Exclusive tests

Normally you could run just a selected test using it.only or a suite of tests using describe.only. Similarly, you could skip a single test or a suite of tests using it.skip and describe.skip methods. These methods are NOT supported by it.each and describe.each. Thus if you want to only run the it.each tests, surround it with its own describe block.

// only run the generated tests
describe.only('my tests', () => {
  it.each(items)(...)
})
// skip these tests
describe.skip('obsolete generated tests', () => {
  it.each(items)(...)
})
// run just these suites of generated tests
describe.only('my suites of tests', () => {
  describe.each(items)(...)
})

Test configuration object

Cypress allows to pass some of its configuration options in the it and describe arguments, see the configuration page. These methods it.each and describe.each do not support this, but you can create a wrapper describe block and set the options there, if needed.

// if a test inside this suite fails,
// retry it up to two times before failing it
describe('user', { retries: 2 }, () => {
  it.each(users)(...)
})

Run specs in parallel

See the explanation in the blog post Refactor Tests To Be Independent And Fast Using Cypress-Each Plugin, but basically you create separate specs file, and each just uses cypress-each to run a subset of the tests

// utils.js
export const testTitle = (selector, k) =>
  `testing ${k + 1} ...`

export const testDataItem = (item) => {
  ...
}

// spec1.js
import { data } from '...'
import { testTitle, testDataItem } from './utils'
it.each(data, 3, 0)(testTitle, testDataItem)

// spec2.js
import { data } from '...'
import { testTitle, testDataItem } from './utils'
it.each(data, 3, 1)(testTitle, testDataItem)

// spec3.js
import { data } from '...'
import { testTitle, testDataItem } from './utils'
it.each(data, 3, 2)(testTitle, testDataItem)

Test case object

Sometimes you just want to have a single object that has all the tests cases together with the inputs. You can pass an object instead of an array to the it.each function. Each object key will become the test title, and the value will be passed to the test callback. If the value is an array, it will be destructured. See object-input.cy.ts spec file for details.

const testCases = {
  // key: the test label
  // value: list of inputs for each test case
  'positive numbers': [1, 6, 7], // [a, b, expected result]
  'negative numbers': [1, -6, -5],
}
it.each(testCases)((a, b, expectedResult) => {
  expect(add(a, b)).to.equal(expectedResult)
})

test case types

Note that in most cases, the it.each(TestCases) tries to "guess" the types from the array value to the test callback function. When you need to, use the utility types to "explain" the value array:

// two arguments
// each value is [number, string]
const toString: TestCaseObject2<number, string> = {
  one: [1, '1'],
  ten: [10, '10'],
}

it.each(toString)((a, b) => {
  // a is a number
  // b is a string
})

// three arguments
const additions: TestCaseObject3<number, number, string> = {
  one: [1, 2, '3'], // a + b in string form
  ten: [10, 20, '30'],
}

it.each(additions)((a, b, s) => {
  expect(String(a + b)).to.equal(s)
})

Specs

Find the implementation in src/index.js

  • it-spec.js uses no shortcuts to define multiple tests that are almost the same. We want to avoid the repetition
  • it-each-spec.js uses the it.each helper to generate multiple it tests given a data array
  • describe-each-spec.js uses describe.each helper to create describe blocks for each item in the given data array
  • mocha-each-spec.js uses 3rd party mocha-each to generate it tests for each data item

Types

This package includes TypeScript definition for it.each and describe.each. Thus the parameter should be the right type from the array of values:

it.each([
  { name: 'Joe', age: 30 },
  { name: 'Mary', age: 20 },
])('has correct types', (user) => {
  // the type for the "user" should be
  // name: string, age: number
  expect(user).to.have.keys('name', 'age')
  expect(user.name).to.be.a('string')
  expect(user.age).to.be.a('number')
})

Include this module with other library types, like

{
  "compilerOptions": {
    "types": ["cypress", "cypress-each"]
  }
}

Or inside an individual spec file add

/// <reference types="cypress-each" />

Small print

Author: Gleb Bahmutov <[email protected]> ยฉ 2021

License: MIT - do anything with the code, but don't blame me if it does not work.

Support: if you find any problems with this module, email / tweet / open issue on Github

MIT License

Copyright (c) 2021 Gleb Bahmutov <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cypress-each's People

Contributors

bahmutov avatar dlgshi avatar jkjustjoshing avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

cypress-each's Issues

Add special placeholder for the iteration index K

it.each(items)('this is item %k', (item) => {
  // the name of the test should be 0, 1, 2 ...
})

it.each(items)('this is item %K', (item) => {
  // the name of the test should be 1, 2, 3 ...
})

Note: util.format does not use %k or %K so we can grab it

unable to use it.only or it.skip or cypress-grep tags with the .each

Hi.
When building tests or debugging its useful to use it.only. But, using this alongside the it.each it's not recognised as a function. It would be handy to have this available with the .each , but not essential.

Also using the cypress-grep tags alongside a test using .each, it fails as well. Being able to tag tests would be amazing.

If you know a way to make this work please share. Thanks

Can functionality be added to work with tags

Hi,

Would it be possible to use this alongside @cypress/grep.

Currently it throws an error:

describe.each(testRun)("new sale", { tags: "@smoke" }, (testCase) => {
  const tc = require(`../../fixtures/salesforce/${testCase}.json`);

  it.each(tc.newSale)(
    (test) => test.tcName,
    (test) => {
      cy.log(test.tcName);
    },
  );
});

Screenshot 2023-07-18 at 14 59 56

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/badges.yml
.github/workflows/ci.yml
  • cypress-io/github-action v6
  • cycjimmy/semantic-release-action v4
npm
package.json
  • cypress 13.7.0
  • cypress-expect 2.5.3
  • semantic-release 23.0.4

  • Check this box to trigger a request for Renovate to run again on this repository

Read from array of objects

Hi I am reading test data from json fixture with typescript typing like this:

import { sites } from '../../../fixtures/api/sites.json'
...
let tests: SiteAccessTestData = sites;  // to specify the type of sites
...
it.each(tests)(testTitle, testElementSelector);

Got this error
> Do not know how to create tests from the values array / object. See DevTools console

When I directly do
it.each(sites)(testTitle, testElementSelector);

It works. Is there a way to force sites to satisfy the type definition SiteAccessTestData while able to use it in cypress-each?

Add helper for splitting a list of items

Across multiple specs, like saying "this spec should take N items, split them into X buckets and only do bucket index K"

// this is the spec index 1 (of 5)
it.each(items, 1, 5)

// in another spec
// this is the spec index 0 (of 5)
it.each(items, 0, 5)

// in another spec
// this is the spec index 4 (of 5)
it.each(items, 4, 5)

Only compatible with webpack

Hi, I have a vite based project and I was trying to use cypress-each in my project, but it doesn't work with it because of webpack based implementation in index.js

// standard Node module "util" has "format" function
const { format } = require('util')

Is it possible to make it compatible for vite based projects as well?
Thanks!

Add types

to make sure it.each and describe.each work

Webpack Compilation Error on Cypress 13

I am in the process of upgrading from Cypress 12 to 13, but the specs that use cypress-each are failing at load time. I am using the latest cypress-each. I do not know what else to try to make this work :-(

Error: Webpack Compilation Error
Module not found: Error: Can't resolve 'process/browser.js' in '/Users/superman/wrk/my-repos/node_modules/util'

Cannot read properties of undefined (reading 'module')
    at Watching.handle [as handler] (/Users/superman/Library/Caches/Cypress/13.6.0/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/webpack-preprocessor/dist/index.js:212:23)
    at /Users/superman/Library/Caches/Cypress/13.6.0/Cypress.app/Contents/Resources/app/node_modules/webpack/lib/Watching.js:303:9
    at Hook.eval [as callAsync] (eval at create (/Users/superman/Library/Caches/Cypress/13.6.0/Cypress.app/Contents/Resources/app/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Watching._done (/Users/superman/Library/Caches/Cypress/13.6.0/Cypress.app/Contents/Resources/app/node_modules/webpack/lib/Watching.js:299:28)
    at /Users/superman/Library/Caches/Cypress/13.6.0/Cypress.app/Contents/Resources/app/node_modules/webpack/lib/Watching.js:213:21
    at Compiler.emitRecords (/Users/superman/Library/Caches/Cypress/13.6.0/Cypress.app/Contents/Resources/app/node_modules/webpack/lib/Compiler.js:919:5)

Allow test title to be a function

That takes the arguments and returns a string to be used as a test title

const items = [...]

function makeTestTitle(item, k, items) {
  return `testing ${item.name}`
}

it.each(items)(makeTestTitle, (item) => ...)

Problem with dynamically specifying array for each

I need to fetch the array from an API.
As example, from here:
https://jsonplaceholder.cypress.io/users?_limit=3

This needs to be done prior to running any of the tests, and so I wish add it to the before() or beforeEach() functions, save them into a variable (or alias) and then use in the tests. I try this but it fails:

describe.only('my tests', function () {
        beforeEach(() => {
            cy.request(
                "GET",
                "https://jsonplaceholder.cypress.io/users?_limit=3"
            ).its('body')
            .as('data')
        })
        
        it.each(this.data)('has correct types', function (item) {
            expect(item.id).to.be.a('number')
            expect(item.name).to.be.a('string')
        })
    })

(code based on my understanding of docs here)

But I keep getting this error:

cypress-each: values must be an array
image

Can you help me identify what I am doing wrong?

Allow a single object with label key and value for tests

Maybe we should be able to create tests from a single object automatically converted into a list

import {add} from './math'

const testCases = {
  // key: the test label
  // value: list of inputs for each test case
  'positive numbers': [1, 6, 7], // [a, b, expected result]
  'negative numbers': [1, -6, -5],
}

it.each(testCases)((a, b, expectedResult) => {
  expect(add(a, b)).to.equal(expectedResult)
})

string title function with array of arrays

// cypress/e2e/title-position.cy.js

describe('Positional title arguments', () => {
  const list = [['foo', 'main']]

  // @ts-ignore
  it.each(list)('title is %1 and %0', (a, b) => {
    expect(a, 'first').to.equal('foo')
    expect(b, 'second').to.equal('main')
    // @ts-ignore
    expect(this.test.title, 'computed test title').to.equal(
      'title is main and foo',
    )
  })
})

Need to use ts-ignore otherwise getting an error

$ npm run lint

> [email protected] lint
> tsc --pretty --allowJs --strict --noEmit src/index.js cypress/**/*.js cypress/**/*.ts

cypress/e2e/title-position.cy.js:9:39 - error TS2345: Argument of type '(this: Context, a: any, b: any) => void' is not assignable to parameter of type '(this: Context, ...res: [...string[], any, any]) => void'.
  Types of parameters 'a' and 'res_0' are incompatible.
    Type '[...string[], any, any]' is not assignable to type '[a?: any, b?: any]'.
      Target allows only 2 element(s) but source may have more.

9   it.each(list)('title is %1 and %0', function (a, b) {
                                        ~~~~~~~~


Found 1 error in cypress/e2e/title-position.cy.js:9

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.