[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 lot. In this lesson, we'll see the recommended Cypress best practices for selectors, and why we should prefer the data-cy attribute.

The Selector Playground automatically follows these best practices.

When determining an unique selector it will automatically prefer elements with:

  • data-cy
  • data-test
  • data-testid

 

Assert on Your Redux Store with Cypress

Cypress doesn't provide out-of-the-box ability to make assertions on our frontend stores, so let's expose the store to the tests, and assert on it. We'll use our knowledge of Cypress's asynchronous programming style to access properties and functions on the store using cy.its and cy.invoke.

Inside applicatioin:

if(window.Cypress) {
    window.store = store
}

Inside test:

cy.window().then(($window) => {console.log($window.store)})

or 

cy.window().its('store')

What we want is to be able to make assertions against the state of the store. In order to get the state of the store, we would normally call, getState which is a function, not a property like store. In order to do this, we can call, .invoke.

cy.window().its('store').invoke('getState').then(($state) => { console.log($state)})

 

Create Custom Cypress Commands with better logs

Do you need to reuse complex Cypress calls often (like when accessing the store)?

You can turn them into custom Cypress commands, and even customize their output in the time-traveling debugger, so it's easy to see a snapshot at the point your command ran!

commands:

复制代码
Cypress.Commands.add("store", (stateName = '') => {
    let log = Cypress.log({name: 'store'})

    const cb = (state) => {
        log.set({
            message: JSON.stringify(state),
            consoleProps: () => {
                return state
            }
        })

        return state
    }

    return cy.window({log: false}).then(($window) => { return $window.store.getState() }).then((state) => {
        if (stateName.length > 0) {
            return cy.wrap(state, {log: false}).its(stateName).then(cb)
        } else {
            return cy.wrap(state, {log: false}).then(cb)
        }
    })
})
复制代码

 

Test:

复制代码
cy.store('todos').should('deep.equal', [{
             id: 1,
            text: 'Hello world',
            completed: false
          }, {
            id: 2,
            text: 'Goodnight moon',
            completed: true
          }])

// or       
 cy.store('example.test.first')
复制代码

 

Wrap External Libraries with Cypress

External libraries tend to be synchronous, so how do we integrate other powerful tools into the Cypress framework? This lesson walks us through merging in the Lodash library to Cypress to allow us to slice and dice data to more accurately assert on just the pieces of data we care about.

commands.js

复制代码
const _ = require('lodash')

let loMethods = _.functions(_).map((fn) => { return 'lo_${fn}'})
loMethods.forEach((loFn) => {
    let loName = loFn.replace(/lo_/, '')
Cypress.Commands.add(loFn, {prevSubject: true}, (subject, fn, ...args) => {
    let result = _[loName](subject, fn, ...args)
    Cypress.log({
        name: 'lo_filter',
        message: JSON.stringify(result),
        consoleProps: () => { return result }
    })
    
   return result
})
复制代码

Use:

复制代码
cy.store('todos')
    .lo_find((todo) => { return todo.id == 1})
    .lo_pick('text')
    .should('deep.equal', [
        {
            text: '1st Todo',
        },
        ...
    ])
复制代码

 

Find Unstubbed Cypress Requests with Force 404

Requests that aren't stubbed will hit our real backend. To ensure we've stubbed all our routes, we can use the force404 method to send 404s from any unstubbed routes.

cy.server({force404: true})

 

posted @   Zhentiw  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-09-19 [Typescript] Specify Exact Values with TypeScript’s Literal Types
2018-09-19 [Unit Testing] Unit Test a Function that Invokes a Callback with a Sinon Spy
2018-09-19 [NPM] Create a new project using the npm init <initializer> command
2017-09-19 [CSS] Build a Fluid Loading Animation in CSS
2017-09-19 [Node & Testing] Intergration Testing with Node Express
2017-09-19 [Node] Stateful Session Management for login, logout and signup
2017-09-19 [Node.js] Serve Static Files with Express
点击右上角即可分享
微信分享提示