Use Cypress to test user registration

Let’s write a test to fill out our registration form. Because we’ll be running this against a live backend, we need to generate the user’s information to avoid re-runs from trying to create new users that already exist. There are trade-offs with this approach. You should probably also clean out the application database before all of your tests start (how you accomplish this is pretty application-specific). Also, if your application requires email confirmation, I recommend you mock that on the backend and automatically set the user as confirmed during tests.

Let's create a helper method first.

support/generate.js

import {build, fake} from 'test-data-bot'

const userBuilder = build('User').fields(
{
username: fake(f => f.internet.userName()),
password: fake(f => f.internet.password())
}
) export {userBuilder}

Then, create tests:

e2e/register.js

import {userBuilder} from '../support/generate'

describe('should register a new user', () => {
it('should register a new user', () => {
const user = userBuilder();
cy.visit('/')
.getByText(/register/i)
.click()
.getByLabelText(/username/i)
.type(user.username)
.getByLabelText(/password/i)
.type(user.password)
.getByText(/submit/i)
.click()
.url()
.should('eq', `${Cypress.config().baseUrl}/`)
.window()
.its('localStorage.token')
.should('be.a', 'string')
});
});

Cypress Driven Development

Because Cypress allows you to use all the developer tools you’re used to from Google Chrome, you can actually use Cypress as your main application development workflow. If you’ve ever tried to develop a feature that required you to be in a certain state you’ve probably felt the pain of repeatedly refreshing the page and clicking around to get into that state. Instead, you can use cypress to do that and developer your application entirely in Cypress.

Simulate HTTP Errors in Cypress Tests

Normally I prefer to test error states using integration or unit tests, but there are some situations where it can be really useful to mock out a response to test a specific scenario in an E2E test. Let’s use the cypress server and route commands to mock a response from our registration request to test the error state.

    it(`should show an error message if there's an error registering`, () => {
cy.server()
cy.route({
method: 'POST',
url: 'http://localhost:3000/register',
status: 500,
response: {},
})
cy.visit('/register')
.getByText(/submit/i)
.click()
.getByText(/error.*try again/i)
})

Test user login with Cypress

To test user login we need to have a user to login with. We could seed the database with a user and that may be the right choice for your application. In our case though we’ll just go through the registration process again and then login as the user and make the same assertions we made for registration.

import {userBuilder} from '../support/generate'

describe('should register a new user', () => {
it('should register a new user', () => {
const user = userBuilder();
cy.visit('/')
.getByText(/register/i)
.click()
.getByLabelText(/username/i)
.type(user.username)
.getByLabelText(/password/i)
.type(user.password)
.getByText(/submit/i)
.click() // now we have new user
.getByText(/logout/i)
.click() // login again
.getByText(/login/i)
.click()
.getByLabelText(/username/i)
.type(user.username)
.getByLabelText(/password/i)
.type(user.password)
.getByText(/submit/i)
.click() // verify the user in localStorage
.url()
.should('eq', `${Cypress.config().baseUrl}/`)
.window()
.its('localStorage.token')
.should('be.a', 'string')
.getByTestId('username-display', {timeout: 500})
.should('have.text', user.username)
});
});

Create a user with cy.request from Cypress

We’re duplicating a lot of logic between our registration and login tests and not getting any additional confidence, so lets reduce the duplicate logic and time in our tests using cy.request to get a user registered rather than clicking through the application to register a new user.

import {userBuilder} from '../support/generate'

describe('should register a new user', () => {
it('should register a new user', () => {
const user = userBuilder();
// send a http request to server to create a new user
cy.request({
url: 'http://localhost:3000/register',
method: 'POST',
body: user
})
cy.visit('/')
.getByText(/login/i)
.click()
.getByLabelText(/username/i)
.type(user.username)
.getByLabelText(/password/i)
.type(user.password)
.getByText(/submit/i)
.click() // verify the user in localStorage
.url()
.should('eq', `${Cypress.config().baseUrl}/`)
.window()
.its('localStorage.token')
.should('be.a', 'string')
.getByTestId('username-display', {timeout: 500})
.should('have.text', user.username)
});
});

Keep tests isolated and focused with custom Cypress commands

We’re going to need a newly created user for several tests so let’s move our cy.request command to register a new user into a custom Cypress command so we can use that wherever we need a new user.

Because we need to create user very often in the test, it is good to create a command to simply the code:

//support/commands.js

import {userBuilder} from '../support/generate'

Cypress.Commands.add('createUser', (overrides) => {
const user = userBuilder(overrides);
// send a http request to server to create a new user
cy.request({
url: 'http://localhost:3000/register',
method: 'POST',
body: user
}).then(response => response.body.user)
})

We chain .then() call is to get the created user and pass down to the test.

describe('should register a new user', () => {
it('should register a new user', () => {
cy.createUser().then(user => {
cy.visit('/')
.getByText(/login/i)
.click()
.getByLabelText(/username/i)
.type(user.username)
.getByLabelText(/password/i)
.type(user.password)
.getByText(/submit/i)
.click() // verify the user in localStorage
.url()
.should('eq', `${Cypress.config().baseUrl}/`)
.window()
.its('localStorage.token')
.should('be.a', 'string')
.getByTestId('username-display', {timeout: 500})
.should('have.text', user.username)
})
});
});

[Cypress] install, configure, and script Cypress for JavaScript web applications -- part2的更多相关文章

  1. [Cypress] install, configure, and script Cypress for JavaScript web applications -- part1

    Despite the fact that Cypress is an application that runs natively on your machine, you can install ...

  2. [Cypress] install, configure, and script Cypress for JavaScript web applications -- part3

    Use custom Cypress command for reusable assertions We’re duplicating quite a few commands between th ...

  3. [Cypress] install, configure, and script Cypress for JavaScript web applications -- part4

    Load Data from Test Fixtures in Cypress When creating integration tests with Cypress, we’ll often wa ...

  4. [Cypress] install, configure, and script Cypress for JavaScript web applications -- part5

    Use the Most Robust Selector for Cypress Tests Which selectors your choose for your tests matter, a ...

  5. Cypress系列(3)- Cypress 的初次体验

    如果想从头学起Cypress,可以看下面的系列文章哦 https://www.cnblogs.com/poloyy/category/1768839.html 前言 这里的栗子项目时 Cypress ...

  6. Cypress系列(41)- Cypress 的测试报告

    如果想从头学起Cypress,可以看下面的系列文章哦 https://www.cnblogs.com/poloyy/category/1768839.html 注意 51 testting 有一篇文章 ...

  7. document.write('<script type=\"text/javascript\"><\/script>')

    document.write('<script type=\"text/javascript\"><\/script>')

  8. <script language = "javascript">, <script type = "text/javascript">和<script language = "application/javascript">(转)

          application/javascript是服务器端处理js文件的mime类型,text/javascript是浏览器处理js的mime类型,后者兼容性更好(虽然application/ ...

  9. 2.1 <script>元素【JavaScript高级程序设计第三版】

    向 HTML 页面中插入 JavaScript 的主要方法,就是使用<script>元素.这个元素由 Netscape 创造并在 Netscape Navigator 2 中首先实现.后来 ...

随机推荐

  1. docker系列之基础命令-1

    1.docker基础命令 docker images 显示镜像列表 docker ps 显示容器列表 docker run IMAGE_ID 指定镜像, 运行一个容器 docker start/sto ...

  2. 【php】 php.ini文件位置解析

    配置文件(php.ini)在 PHP 启动时被读取.对于服务器模块版本的 PHP,仅在 web 服务器启动时读取一次.对于CGI 和 CLI 版本,每次调用都会读取. php.ini 的搜索路径如下( ...

  3. PAT Basic 1015

    1015 德才论 宋代史学家司马光在<资治通鉴>中有一段著名的“德才论”:“是故才德全尽谓之圣人,才德兼亡谓之愚人,德胜才谓之君子,才胜德谓之小人.凡取人之术,苟不得圣人,君子而与之,与其 ...

  4. python之动态参数 *args,**kwargs(聚合,打散)

    一.函数的动态参数 *args,**kwargs, 形参的顺序1.你的函数,为了拓展,对于传入的实参数量应该是不固定,所以就需要用到万能参数,动态参数,*args, **kwargs 1,*args  ...

  5. Hive 导入数据报错,驱动版本过低

    Failed with exception Unable to alter table. javax.jdo.JDODataStoreException: You have an error in y ...

  6. git (unable to update local ref )

    https://stackoverflow.com/questions/2998832/git-pull-fails-unable-to-resolve-reference-unable-to-upd ...

  7. Java-获取一个类的父类

    如何使用代码获取一个类的父类 package com.tj; public class MyClass implements Cloneable { public static void main(S ...

  8. Leetcode 322.零钱兑换

    零钱兑换 给定不同面额的硬币 coins 和一个总金额 amount.编写一个函数来计算可以凑成总金额所需的最少的硬币个数.如果没有任何一种硬币组合能组成总金额,返回 -1. 示例 1: 输入: co ...

  9. C#中类的实例是不能 获取到类中的静态方法和静态变量(Static)的,及原因

    类中的静态方法和变量是共享的.只能用类名去调用.

  10. 【bzoj1532】[POI2005]Kos-Dicing 二分+网络流最大流

    题目描述 Dicing 是一个两人玩的游戏,这个游戏在Byteotia非常流行. 甚至人们专门成立了这个游戏的一个俱乐部. 俱乐部的人时常在一起玩这个游戏然后评选出玩得最好的人.现在有一个非常不走运的 ...