[Cycress]install、configure、and script Cycres for JavaScript web appration--part 2

11308 ワード

Use Cyress 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.The are trea-offs with appech.You shoud probably also clean the appication the appration fortaryif your appection requires email confirmation、I recommand you mock that on the backend and atomatially 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}
 
The n、create tests:
e 2 e/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')
    });
});
 
Cyperes Driven Development
Because Cyress allows you to use all the developer tools you're used to from Google Chrome、あなたのcan actually use Cyperes as your main appication development workflow.If you’ve ever tried to develop a feature that required you to be in a certain state out've probably felt the pain of repeedit the freare theあなたのcan use cyperes to do that and developer your appication entirely in Cyress.
 
Simullate HTTP Errers in Cyress Tests
Normally I prefer to test error state s using integration or unit tests、but there re are some situations where it can be really useful to mock out a reponse to a specific scenar in e e e e e e e e e e 2 E 2 E test.Let's thertheress therererererever.
    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 Cyress
 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 chice for your appration.In our case thougwe’ll just go through the registration and the process the
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 Cyress
We’re duplicating a lot of logic between our registration and logists and not getting any addititional confidence,so lets reduce the duplicate logists and time in our tests ing cy.request get a user theregistregistragister
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 Cyress command
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 Cympres command so we can use where we need a neuser.
 
Because we need to create user very oten in the test、it is good 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)
        })
    });
});