How to create fixtures with random data using Cypress and faker
Tags: cypress, fixtures, testing, faker
Published: 2021-10-13 10:26:13

## Random fixtures? Yes, it is possible!

One of these days, in the [**Cypress-BR**](https://t.me/cypress_br) group on Telegram, the following question came up:

> Is it possible to put `faker` on a `.json` file?

The short answer is no.

But, it's possible to create a `.json` file dynamically, using the [**`cy.writeFile`**](https://docs.cypress.io/api/commands/writefile#JSON) functionality, and with the help of the [**`faker`**](https://fakerjs.dev) library, make all data in this file dynamic.

Let's look at an example, creating a [**`fixture`**](https://docs.cypress.io/api/commands/fixture#JSON) for use in a test that mocks the backend and tests the frontend in isolation.

The application under test (AUT) is called [**Hacker Stories**](https://wlsf82-hacker-stories.web.app/).

This application communicates with the [**Hackernews public API**](https://hn.algolia.com/api) for listing stories.

However, as mentioned earlier, we will mock the API.

The test file is as follows.

```js
// cypress/integration/hackerStories.spec.js

describe('Hacker Stories', () => {
  beforeEach(() => {
    cy.generateFixture()

    cy.intercept(
      'GET',
      '**/search?query=React&page=0',
      { fixture: 'stories' }
    ).as('getStories')

    cy.visit('/')
    cy.wait('@getStories')
  })

  it('renders 20 stories, then 19 when dismissing one', () => {
    cy.get('.item').should('have.length', 20)

    cy.get('.button-small').first().click()

    cy.get('.item').should('have.length', 19)
  })
})
```

Note that in the `beforeEach` hook, there is a custom command called `generateFixture()`. We'll see what this command does in a moment.

Also, notice that we are intercepting a request, which we will respond with a fixture called `stories`.

Afterward, we visit the AUT, wait for such mocked request to happen, and the test is executed, which verifies that there are 20 items in the list and that when removing the first one, 19 are left.

You might be curious about the implementation of the `generateFixture()` command, right?

There it goes.

```js
// cypress/support/commands.js

Cypress.Commands.add('generateFixture', () => {
  const faker = require('@faker-js/faker')

  cy.writeFile('cypress/fixtures/stories.json', {
    'hits':Cypress._.times(20, () => {
      return {
        'title':`${faker.lorem.words(3)}`,
        'url':`${faker.internet.url()}`,
        'author':`${faker.name.firstName()} ${faker.name.lastName()}`,
        'num_comments':`${faker.datatype.number()}`,
        'points':`${faker.datatype.number()}`,
        'objectID':`${faker.datatype.uuid()}`,
      }
    })
  })
})
```

For the random data, we import `faker` to the command, using JavaScript's `require` function.

Then we use `cy.writeFile`, to write a file called `stories.json` in the `cypress/fixtures/` directory. As a second argument, we pass an object, which will contain the value of that file.

Such an object will have a `hits` property, which is exactly what the frontend expects, and that property expects an array of objects.

We use lodash's [**`.times`**](https://lodash.com/docs/4.17.15#times) functionality (which is bundled with Cypress), as it returns precisely an array.

Then the `.times` function runs 20 times to create 20 random stories, each with its `title`, `url`, `author`, `num_comments`, `points`, and `objectID`, using different functionalities offered by the `faker` library.

For an example of the created fixture, access [**this file**](https://github.com/wlsf82/dynamic-fixtures/blob/main/cypress/fixtures/example.json).

**Note:** Since this fixture is dynamic, we must add it to the [**`.gitignore`**](https://github.com/wlsf82/dynamic-fixtures/blob/main/.gitignore#L3) file, cause we don't want to version it.

And so, we have a test that consumes a dynamically created fixture with random data. 🥳

That is, for each run, the fixture will be overwritten with new data.

___

I invite you to clone the project on your computer, install the dependencies following the documentation and then run the tests (both in interactive and in headless mode).

[**Access the complete project on GitHub**](https://github.com/wlsf82/dynamic-fixtures).

Take the opportunity to leave a ⭐.

___

**Note 2:** As an alternative to the proposed solution, check out [**this other one**](https://github.com/wlsf82/dynamic-fixtures/commit/f8925dbfd6186cbc8c09eda1b2c85d6b48996296), where instead of using fixtures, we overwrite the request response's body.

___

Did you like the content? Leave a comment!

___

Curious and want to learn more about **Cypress Testing Automation**? Check out my courses on [**Udemy**](https://udemy.com/user/walmyr).

___

👋 Until next time and happy testing!

___

This post was originally published in Portuguese at the [**Talking About Testing**](https://talkingabouttesting.com/2021/09/13/como-criar-fixtures-com-dados-aleatorios-com-cypress-e-faker/) blog.