0
votes

I'm trying to use cy.writeFile to write my fixture files against an api. I need these fixture files to be generated before any Cypress tests run, since all the tests will use these fixture files. I only need this to be run one time, before any tests run, not before each test.

I've tried adding a before function to the /cypress/support/index.js file but it doesn't create the fixture files when I run "cypress run".

import './commands'

before(function() {
   // runs once before all tests in the block
    const apiUrl = 'http://localhost:8080/api/';
    const fixturesPath = 'cypress/fixtures/';
    const fixtureExtension = '.json';

    let routePath = 'locations';
    cy.request(`${apiUrl}${routePath}`).then((response) => {
      cy.writeFile(`${fixturesPath}${path}${fixtureExtension}`, response.body);
    });
 });

Shouldn't this before hook run before any of my tests using "cypress run" run?

1

1 Answers

0
votes

Yes, it should run before any of your tests.

The fixture is not created because the request fails. It's due to any number of reasons, for instance: the api is not ready when Cypress runs, or it requires authentication ... you'd better double-check that.

I made an example here. Before starting cypress yarn cy:run, you have to make sure both the api server (yarn start:mock) and webserver (yarn start) are ready.


Another note that the before() function in support/index.js is not run one time because it's included in every test suite so let's say you have 3 test files, then it's executed 3 times.