Commit cc5d7184 authored by Alexandros Georgantas's avatar Alexandros Georgantas

Merge branch 'cypress' into 'master'

Cypress

See merge request editoria/ucp!17
parents 2fd39b14 c4308e4f
# How to write new E2E tests
Editoria uses Cypress to run end to end tests.
Follow the steps below to get up and running:
Make sure your test db is running:
If you have already run `yarn start:services` you should have two Postgres Docker containers running (one for development and one for testing). It might be good to look at the `docker-compose.yml` file in the application’s root folder. Worth noting is that the test db doesn’t have a data folder, as no data is meant to be persisted.
Create and source a `test.env` file (by convention inside the config folder). This should be the same as the development environment file, apart from the following values:
```
NODE_ENV=’test’
POSTGRES_DB=’test’
POSTGRES_USER=’test’
POSTGRES_PASSWORD=’pass’
POSTGRES_PORT=’5433’
```
Once you’ve sourced the `test.env` file, run `yarn setupdb` and create an admin account with username `admin` and password `password`. If you’ve done this step once for the testing db, you don’t need to do it again.
Bring up the server with `yarn server`.
On another terminal window / tab, run `yarn cypress`. This should bring the Cypress app up.
You can run the existing tests by clicking on the “Run all tasks” button at the top right. The tests will run in a browser window.
To make a new test, simply create a new file (eg. `mytest_spec.js`) inside the Cypress/integration folder on your app. You can use the rest of the files in there for reference. If you need to test a page that needs an authenticated user, use the login command to sign in as a particular role (eg. cy.login(‘author’). Should you need to seed data before your tests, you can execute a seed script in a before hook (eg. `cy.exec(filePath)`). You can take a look at `dashboard_spec.js` for an example of this.
You’re all set!
# Detailed instructions on seeding the database before running a test
In order to test your app you need to have data in your database. That means before you run your tests you should seed your database.
You generally have three ways to facilitate this with Cypress:
* `cy.exec()` - to run system commands
* `cy.task()` - to run code in Node.js via the pluginsFile
* `cy.request()` - to make HTTP requests
In Editoria we are going to use the first approach. We are going to create scripts that can populate the database with data or scripts that truncate the database and then we executed with `cy.exec()`.
All we need is creating the script that we want to run for each test and call it before each test.
## Dashboard example
An example test could be a dashboard test, where certain books need to show up and be assigned to certain users.
So first thing is to create a script called e.g. `createBooksWithUsersAndTeams.js` which creates books and assigns’ them to admin and author user: https://gitlab.coko.foundation/editoria/ucp/blob/cypress/scripts/createBooksWithUsersAndTeams.js
And last but not least we should call that script by using ‘before’ and ‘beforeEach’ functions of Cypress like the example below.
```
beforeEach(() => {
cy.exec('node ./scripts/truncateDB.js')
cy.exec('node ./scripts/createBooksWithUsersAndTeams.js')
})
```
......@@ -56,13 +56,7 @@ module.exports = {
},
mailer: {
from: 'dev@example.com',
transport: {
host: 'smtp.mailgun.org',
auth: {
user: 'dev@example.com',
pass: 'password',
},
},
path: path.join(__dirname, 'mailer'),
},
publicKeys: [
'authsome',
......@@ -93,6 +87,7 @@ module.exports = {
logger,
port: 3000,
uploads: 'uploads',
pool: { min: 0, max: 10, idleTimeoutMillis: 1000 },
},
'@pubsweet/component-polling-server': {
timer: 10000,
......
module.exports = {
transport: {
host: 'smtp.mailgun.org',
auth: {
user: 'dev@example.com',
pass: 'password',
},
},
}
const { deferConfig } = require('config/defer')
const path = require('path')
const winston = require('winston')
require('winston-daily-rotate-file')
const logger = new winston.Logger({
transports: [
new winston.transports.Console({
colorize: true,
}),
new winston.transports.DailyRotateFile({
filename: 'app-%DATE%.log',
dirname: path.join(__dirname, '../logs/dev'),
datePattern: 'DD-MM-YYYY',
zippedArchive: true,
maxFiles: '30d',
json: true,
handleExceptions: true,
humanReadableUnhandledException: true,
}),
],
})
module.exports = {
'pubsweet-server': {
baseUrl: deferConfig(
cfg => `http://localhost:${cfg['pubsweet-server'].port}`,
),
logger,
pool: { min: 0, max: 10, idleTimeoutMillis: 1000 },
},
'pubsweet-component-ink-backend': {
inkEndpoint: 'http://dummyURL.com/',
email: 'user@example.com',
password: 'somepassword',
recipes: {
'editoria-typescript': '2',
},
},
}
{
"baseUrl": "http://localhost:4000"
}
{
"env": {
"cypress/globals": true
},
"extends": ["plugin:cypress/recommended"],
"plugins": ["cypress"],
"rules": {
"jest/valid-expect": 0
}
}
[
{
"title": "Author Book",
"teamMember": ["author"]
},
{
"title": "Production Editor Book",
"teamMember": ["productionEditor"]
},
{
"title": "Copy Editor Book",
"teamMember": ["copyEditor"]
}
]
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}
\ No newline at end of file
{
"id": 8739,
"name": "Jane",
"email": "jane@example.com"
}
\ No newline at end of file
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},
{
"id": 4,
"name": "Patricia Lebsack",
"username": "Karianne",
"email": "Julianne.OConner@kory.org",
"address": {
"street": "Hoeger Mall",
"suite": "Apt. 692",
"city": "South Elvis",
"zipcode": "53919-4257",
"geo": {
"lat": "29.4572",
"lng": "-164.2990"
}
},
"phone": "493-170-9623 x156",
"website": "kale.biz",
"company": {
"name": "Robel-Corkery",
"catchPhrase": "Multi-tiered zero tolerance productivity",
"bs": "transition cutting-edge web services"
}
},
{
"id": 5,
"name": "Chelsey Dietrich",
"username": "Kamren",
"email": "Lucio_Hettinger@annie.ca",
"address": {
"street": "Skiles Walks",
"suite": "Suite 351",
"city": "Roscoeview",
"zipcode": "33263",
"geo": {
"lat": "-31.8129",
"lng": "62.5342"
}
},
"phone": "(254)954-1289",
"website": "demarco.info",
"company": {
"name": "Keebler LLC",
"catchPhrase": "User-centric fault-tolerant solution",
"bs": "revolutionize end-to-end systems"
}
},
{
"id": 6,
"name": "Mrs. Dennis Schulist",
"username": "Leopoldo_Corkery",
"email": "Karley_Dach@jasper.info",
"address": {
"street": "Norberto Crossing",
"suite": "Apt. 950",
"city": "South Christy",
"zipcode": "23505-1337",
"geo": {
"lat": "-71.4197",
"lng": "71.7478"
}
},
"phone": "1-477-935-8478 x6430",
"website": "ola.org",
"company": {
"name": "Considine-Lockman",
"catchPhrase": "Synchronised bottom-line interface",
"bs": "e-enable innovative applications"
}
},
{
"id": 7,
"name": "Kurtis Weissnat",
"username": "Elwyn.Skiles",
"email": "Telly.Hoeger@billy.biz",
"address": {
"street": "Rex Trail",
"suite": "Suite 280",
"city": "Howemouth",
"zipcode": "58804-1099",
"geo": {
"lat": "24.8918",
"lng": "21.8984"
}
},
"phone": "210.067.6132",
"website": "elvis.io",
"company": {
"name": "Johns Group",
"catchPhrase": "Configurable multimedia task-force",
"bs": "generate enterprise e-tailers"
}
},
{
"id": 8,
"name": "Nicholas Runolfsdottir V",
"username": "Maxime_Nienow",
"email": "Sherwood@rosamond.me",
"address": {
"street": "Ellsworth Summit",
"suite": "Suite 729",
"city": "Aliyaview",
"zipcode": "45169",
"geo": {
"lat": "-14.3990",
"lng": "-120.7677"
}
},
"phone": "586.493.6943 x140",
"website": "jacynthe.com",
"company": {
"name": "Abernathy Group",
"catchPhrase": "Implemented secondary concept",
"bs": "e-enable extensible e-tailers"
}
},
{
"id": 9,
"name": "Glenna Reichert",
"username": "Delphine",
"email": "Chaim_McDermott@dana.io",
"address": {
"street": "Dayna Park",
"suite": "Suite 449",
"city": "Bartholomebury",
"zipcode": "76495-3109",
"geo": {
"lat": "24.6463",
"lng": "-168.8889"
}
},
"phone": "(775)976-6794 x41206",
"website": "conrad.com",
"company": {
"name": "Yost and Sons",
"catchPhrase": "Switchable contextually-based project",
"bs": "aggregate real-time technologies"
}
},
{
"id": 10,
"name": "Clementina DuBuque",
"username": "Moriah.Stanton",
"email": "Rey.Padberg@karina.biz",
"address": {
"street": "Kattie Turnpike",
"suite": "Suite 198",
"city": "Lebsackbury",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "ambrose.net",
"company": {
"name": "Hoeger LLC",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}
]
\ No newline at end of file
describe('BookBuilder', () => {
before(() => {
cy.exec('node ./scripts/truncateDB.js')
cy.exec('node ./scripts/createBooksWithUsersAndTeams.js')
})
it('production editor can navigate to book builder for the book she/he is assigned on', () => {
cy.login('productionEditor')
cy.getCollections().then(res => {
const { body } = res
const { data } = body
const { getBookCollections } = data
const collection = getBookCollections[0]
const { books } = collection
const productionEditorBook = books[0]
cy.visit(`/books/${productionEditorBook.id}/book-builder`)
cy.contains('FRONTMATTER')
cy.contains('BODY')
cy.contains('BACKMATTER')
})
})
})
describe('Dashboard', () => {
before(() => {
cy.exec('node ./scripts/truncateDB.js')
cy.exec('node ./scripts/createBooksWithUsersAndTeams.js')
})
it('shows dashboard', () => {
cy.login('admin')
cy.visit('/books')
cy.contains('Books')
})
it('admin can add books', () => {
cy.login('admin')
cy.visit('/books')
cy.get('[data-cy="add-book-btn"]').should('have.length', 1)
cy.get('[data-cy="add-book-btn"]').should('not.be.disabled')
})
it('global production editor can add books', () => {
cy.login('globalProductionEditor')
cy.visit('/books')
cy.get('[data-cy="add-book-btn"]').should('have.length', 1)
cy.get('[data-cy="add-book-btn"]').should('not.be.disabled')
})
it('production editor can not add books', () => {
cy.login('productionEditor')
cy.visit('/books')
cy.get('[data-cy="add-book-btn"]').should('have.length', 0)
})
it('copy editor can not add books', () => {
cy.login('copyEditor')
cy.visit('/books')
cy.get('[data-cy="add-book-btn"]').should('have.length', 0)
})
it('author can not add books', () => {
cy.login('author')
cy.visit('/books')
cy.get('[data-cy="add-book-btn"]').should('have.length', 0)
})
it('admin can see all three books', () => {
cy.login('admin')
cy.visit('/books')
cy.get('[data-cy="book"]').should('have.length', 3)
})
it('global production editor can not see any book', () => {
cy.login('globalProductionEditor')
cy.visit('/books')
cy.get('[data-cy="book"]').should('have.length', 0)
})
it('production editor can see only assigned books (1)', () => {
cy.login('productionEditor')
cy.visit('/books')
cy.get('[data-cy="book"]').should('have.length', 1)
cy.get('[data-cy="book"]').contains('Production Editor Book')
})
it('copy editor can see only assigned books (1)', () => {
cy.login('copyEditor')
cy.visit('/books')
cy.get('[data-cy="book"]').should('have.length', 1)
cy.get('[data-cy="book"]').contains('Copy Editor Book')
})
it('author can see only assigned books (1)', () => {
cy.login('author')
cy.visit('/books')
cy.get('[data-cy="book"]').should('have.length', 1)
cy.get('[data-cy="book"]').contains('Author Book')
})
})
const { admin } = require('../support/credentials')
describe('Login page', () => {
it('is there', () => {
cy.visit('/')
const { username, password } = admin
cy.get('input[name="username"]').type(username)
cy.get('input[name="password"]').type(password)
cy.get('button[type="submit"]').click()
cy.url().should('include', '/books')
})
})
const { user1 } = require('../support/credentials')
const checkFormError = message => {
cy.get('div[role=alert]').each($el => {
if ($el[0].innerHTML !== '') {
cy.wrap($el)
.contains(message)
.should('be.visible')
}
})
}
describe('Signup page', () => {
beforeEach(() => {
cy.exec('node ./scripts/truncateDB.js')
})
it('loads signup page', () => {
cy.visit('/signup')
cy.contains('Sign up')
})
it('successfully creates user', () => {
cy.visit('/signup')
const { givenName, surname, email, username, password } = user1
cy.get('input[name="givenName"]').type(givenName)
cy.get('input[name="surname"]').type(surname)
cy.get('input[name="username"]').type(username)
cy.get('input[name="email"]').type(email)
cy.get('input[name="password"]').type(password)
cy.get('button[type="submit"]').click()
cy.url().should('include', '/login')
cy.get('input[name="username"]').type(username)
cy.get('input[name="password"]').type(password)
cy.get('button[type="submit"]').click()
cy.url().should('include', '/books')
})
it('fails if required fields not filled in', () => {
const { givenName, surname } = user1
cy.visit('/signup')
cy.get('input[name="username"]')
.focus()
.blur()
cy.get('input[name="email"]')
.focus()
.blur()
cy.get('input[name="password"]')
.focus()
.blur()
cy.get('button[type="submit"]').should('be.disabled')
checkFormError('Required')
cy.get('input[name="givenName"]').type(givenName)
cy.get('input[name="surname"]')
.focus()
.blur()
checkFormError('Required')
cy.get('input[name="surname"]').type(surname)
cy.get('input[name="givenName"]')
.clear()
.blur()
checkFormError('Required')
})
})
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
// const createBooksWithUsersAndTeams = require('../../scripts/createBooksWithUsersAndTeams')
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('task', {})
}
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This is will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
const credentials = require('./credentials')
Cypress.Commands.add('login', role => {
const { username, password } = credentials[role]
const loginUserMutation = `mutation{
loginUser (input: {
username: "${username}",
password: "${password}"
}) {
token
}
}`
window.localStorage.removeItem('token')
cy.request({
method: 'POST',
url: '/graphql',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: { query: loginUserMutation },
}).then(response => {
const { token } = response.body.data.loginUser
window.localStorage.setItem('token', token)
})
})
Cypress.Commands.add('getCollections', () => {
const token = window.localStorage.getItem('token')
const getCollectionsQuery = `query(
$ascending: Boolean = true
$archived: Boolean = false
$sortKey: String = "title"
) {
getBookCollections {
id
title
books(ascending: $ascending, sortKey: $sortKey, archived: $archived) {
id
title
publicationDate
isPublished
archived
authors {
username
givenName
surname
}
}
}
}
`
return cy.request({
method: 'POST',
url: '/graphql',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
authorization: token ? `Bearer ${token}` : '',
},
body: { query: getCollectionsQuery },
})
})
const credentials = {
admin: {
username: 'admin',
password: 'password',
},
user1: {
givenName: 'John Travolta',
surname: 'actor',
username: 'user1',
password: '123456789',
email: 'john.travolta@awesome.com',
},
author: {
username: 'author',
password: 'password',
},
productionEditor: {
username: 'productionEditor',
password: 'password',
},
globalProductionEditor: {
username: 'globalProductionEditor',
password: 'password',