[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 the registration and login of our user for assertions. Let’s see how we can take these assertions and create a custom command to make the assertions.

We have the tests:

    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)
        })
    });

We can create some assertions commands to make it more reusable:

Cypress.Commands.add(‘assertHome‘, () => {
  cy.url().should(‘eq‘, `${Cypress.config().baseUrl}/`)
})

Cypress.Commands.add(‘assertLoggedInAs‘, user => {
  cy
    .window()
    .its(‘localStorage.token‘)
    .should(‘be.a‘, ‘string‘)
    .getByTestId(‘username-display‘, {timeout: 500})
    .should(‘have.text‘, user.username)
})

Then we can improve the test:

    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()
            .assertHome()
            .assertLoggedInAs(user);
        })
    });

Run tests as an authenticated user with Cypress

For most applications you’re going to need to be logged in as a user to interact with the application. Let’s see how we can register as a new user and login as that user to test using the application as a logged in user.

Sometime you want to check some DOM element is not present, you cna use queryByTestId()

    it(‘displays the username‘, () => {
        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()
                .assertLoggedInAs(user)
                .getByText(/logout/i)
                .click()
                .queryByTestId(‘username-display‘, {timeout: 300})
                .should(‘not.exist‘)
        })
    });

Combine custom Cypress commands into a single custom command

Almost every time we need to login, we’ll want to have a newly created user to login as. Let’s go ahead and combine the createNewUser and logincommands to create a single loginAsNewUser which we can use in any test that needs an authenticated user.

// support/commands.js

Cypress.Commands.add(‘loginAsNewUser‘, () => {
    cy.createUser().then(user => {
        cy.login(user)
    });
});

Cypress.Commands.add(‘login‘, user => {
    cy.request({
        url: ‘http://localhost:3000/login‘,
        method: ‘POST‘,
        body: user,
    }).then(({body}) => {
        window.localStorage.setItem(‘token‘, body.user.token);
        return body.user;
    })
})
// e2e/calcualtor.js

describe(‘authenticated calculator‘, () => {
    it(‘displays the username‘, () => {
        cy.loginAsNewUser().then((user) => {
            cy.visit(‘/‘)
            .getByTestId(‘username-display‘)
            .should(‘have.text‘, user.username)
            .getByText(/logout/i)
            .click()
            .queryByTestId(‘username-display‘, {timeout: 300})
            .should(‘not.exist‘)
        })
    });
})

Install React DevTools with Cypress

Because Cypress runs in a real Chrome browser, we can install extensions, like React DevTools. The tricky bit will be to make our application hook up to the extension properly.

react-dev-tools.js

if (window.Cypress) {
    window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__
  }

Import the script before we import the REACT

index.js

import ‘./react-dev-tools‘

import ‘./global.css‘
import React from ‘react‘

原文地址:https://www.cnblogs.com/Answer1215/p/10079585.html

时间: 2024-10-12 11:50:07

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

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

application/javascript是服务器端处理js文件的mime类型,text/javascript是浏览器处理js的mime类型,后者兼容性更好(虽然application/javascript才是正确写法,由于现在大家都写错的,导致浏览器厂商对写application/javascript兼容性更好).等以后大家都用HTML5的时候,就不需要写这个了.直接<script></script>就OK了! 另外 <script language = "ja

2.1 &lt;script&gt;元素【JavaScript高级程序设计第三版】

向 HTML 页面中插入 JavaScript 的主要方法,就是使用<script>元素.这个元素由 Netscape 创造并在 Netscape Navigator 2 中首先实现.后来,这个元素被加入到正式的 HTML 规范中. HTML 4.01 为<script>定义了下列 6 个属性. async:可选.表示应该立即下载脚本,但不应妨碍页面中的其他操作,比如下载其他资源或等待加载其他脚本.只对外部脚本文件有效. charset:可选.表示通过 src 属性指定的代码的字符

Yeoman - scaffold JavaScript Web Application

Yeoman - scaffold JavaScript Web Application (setup new JavaScript web app quickly) depend on two tools:-Grunt, JavaScript task runner-Bower, A package manager for web step0, install Node.js and NPMstep1, install Grunt: # npm install -g grunt-clistep

web前端之MVC的JavaScript Web富应用开发一:MVC和类

web前端之MVC的JavaScript Web富应用开发一:MVC和类 开篇: 本书以 assert() 和 assertEqual() 函数来展示变量的值或者函数调用的结果. assert() 是一种快捷表述方式, 用来表示一个特定的变量( revolves to true). 这在自动化测试中是一种非常常见的模式. assert() 可以接收两个参数 : 一个值和一个可选的消息. 如果运行结果不是真值, 这个函数将抛出一个异常 : var assert = function(value,

MooTools---开源JavaScript web应用框架

MooTools is a collection of JavaScript utilities designed for the intermediate to advanced JavaScript developer. It allows you to write powerful and flexible code with its elegant, well documented, and coherent APIs. MooTools code is extensively docu

Javascript web知识

浏览器中的JavaScript很重要的一部分是BOM(浏览器对象模型),她提供了独立于内容而与浏览器窗口进行交互的对象. 1. 导航和打开新窗口 window.open(“http://www.baidu.com”,”wioxwindow”, ”height=150,width=30,top=10,left=10,resizable=yes”); 特性字符串是用逗号分隔的,因此在逗号或等号前后不能有空格. window.open( pageURL,name,parameters); 其中: pa

试读《基于MVC的JavaScript Web富应用开发》— 不一样的JavaScript

前言 <基于MVC的JavaScript Web富应用开发>是ItEye在7月份发起试读的书.下载了试读的章节,发现只有全本的开始到第二章,第一章很简洁明了地讲述了JavaScript的历史,怎么用JavaScript实现类,基本JavaScript的MVC的概念:第二章是浏览器的事件机制,DOM的事件监听,JQuery事件绑定的例子. 值得一提的是,这本书原本是O’Reilly Media, Inc带来的.O’Reilly的一系列“动物书”总是经典. 最大的感触:JavaScript的MVC

10个优秀的JavaScript Web UI库/框架推荐

在进行Web开发时,并非所有的库都适合你的项目,但你仍需要收藏一些Web UI设计相关的库或框架,以在你需要的时候,加快你的开发效率. 本文为你带来10款非常优秀的基于JavaScript的Web UI设计资源. 1.  XUI:JavaScript微型框架 这是一个“轻量级.非常简单.微型.超级模块化”的JavaScript框架,用于创建移动Web应用.该框架如此轻量级的原因是一些与浏览器兼容相关的代码被剥离. 2.  iUI:iPhone UI 框架 该框架由JavaScript库.CSS和

微软的dotnet-new工具可以使创建JavaScript Web 程序变得更简单

Microsoft发布了一组工具,使用他们的dotnet-new工具和使用Node.js的灵活方法可以快速生成基于JavaScript的Web 应用程序. dotnet-new工具是.NET Core工具的一部分,用于使用简单的命令启动一个新项目.作为ASP.NET Core JavaScript Services的一部分,Web开发人员现在可以使用相同的命令来启动新的单页应用程序(SPA). Steve Sanderson在一篇文章中写道,使用这些模板的目的是让初始更容易:"我们经常听说构建这