Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve SPA before running tests on cypress js

With Cypress I can test my dev subdomain easily. I have an angular/react application where when I make a dist (including index.html), I want to run Cypress tests against the built files.

Unfortunately, I have no idea how to serve a dist folder, (like serve package of npm) before starting Cypress tests.

I know that I can serve the index.html on another terminal tab, but this is not going to happen on CircleCi (my CI).

Is there anyway that Cypress can replace the localhost and serve static files before starting the actual tests?

like image 289
Alex Avatar asked Dec 24 '17 04:12

Alex


2 Answers

I used browser-sync to launch a server that distribute my static files.

You need to install 3 packages: cypress (obviously), browser-sync to launch a server, and npm-run-all to launch a server and cypress consecutively.

npm install --save-dev cypress
npm install --save-dev browser-sync
npm install --save-dev npm-run-all

Here is an example of the npm scripts configuration that you will need to add in your package.json. Don't forget to customize the <port> (ex: 4000) and <folder> that contains the path to your SPA (ex: public).

{
  "scripts": {
    "cypress": "cypress run",
    "server": "browser-sync start --port <port> --server <folder> --no-open",
    "test": "run-p -r server cypress"
  }
}

Now you have to write your first Hello world test:

describe('My App', function() {
    it('is up', function() {
        cy.visit('http://localhost:4000');

        cy.contains('Hello world!');
    });
});

That's it! We can launch our test:

npm test
like image 67
tzi Avatar answered Oct 20 '22 18:10

tzi


I did the following:

I installed

npm i serve

and added

serve: "serve -s <build-folder>"

to my package.json. And then in your e.g. travis.yml you add

- npm run serve & 
- npm test

The & at the end of your command will make it run in the backend and thus the test can run right after it. Since serve is pretty fast serving the static files there is no need for the npm test to wait either AND you do not have to worry about stopping the npm run serve afterwards since most CI environments are cleaning up background processes automatically after your tests finished.

Most of the information above can also be found here.

like image 33
Jonathan Avatar answered Oct 20 '22 18:10

Jonathan