Getting started with Cypress - E2E Testing Framework

๐Ÿ‘‘ Goal

Set up Cypress with React App

โš”๏ธ Create Reac app

1
2
npx create-react-app react-cypress
cd react-cypress

โš”๏ธ Install cypress

1
yarn add -D cypress@3.5.0

โš”๏ธ Add a new script to package.json

1
"cy": "./node_modules/.bin/cypress open"

โš”๏ธ Check if cypress works

1
yarn cy

This opens Cypress Test Runner.

Cypress Test Runner

โš”๏ธ Create a new test

Add a file named sample.spec.js in cypress/integration directory

1
2
3
4
5
describe('Cypress', () => {
it('is working', () => {
expect(true).to.equal(true);
});
});

โš”๏ธ Restart cypress (yarn cy)

Click sample.spec.js (this runs the test)
(or yarn cypress run -spec ./cypress/integration/sample.spec.js)
You should be happy now ๐Ÿ˜ƒ

โš”๏ธ Edit App.js to make it counter app

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { useState } from 'react';

function App() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div className='App' style={{ textAlign: 'center' }}>
<span>count: </span>
<span className='counter'>{count}</span>
<div>
<button className='increment' onClick={increment}>
+
</button>
</div>
</div>
);
}

export default App;

Check if it works with yarn start
counter

โš”๏ธ Edit cypress.json to add url

1
2
3
4
{
"baseUrl": "http://localhost:3000/",
"video": false
}

โš”๏ธ Add counter.spec.js in cypress/integration direactory

1
2
3
4
5
6
7
8
9
10
11
12
13
// counter.spec.js

describe('Counter Test', () => {
beforeEach(() => {
cy.visit('/');
});

it('successfully loads3434343', () => {
cy.get('.increment').click();
cy.contains('.counter', 1);
// cy.get('.counter').should('have.text', '1');
});
});

โš”๏ธ Run test

1
yarn cy

Click counter.spec.js in Cypress Test Runner

Cypress Test Runner

๐Ÿดโ€โ˜ ๏ธError with Cypress 4.5โ€ฆ

I encountered an error with Cypress 4.5. hmmmโ€ฆ ๐Ÿค” ๐Ÿค” ๐Ÿค”

error on Cypress 4.5

๐Ÿ”ฎ Ref

https://docs.cypress.io/guides/getting-started/installing-cypress.html#System-requirements