Alex-Programer

Alex-Programer

随缘博客,不定期更新不确定的内容~
github
twitter

Cypress User Manual

Version ^11.2.0#

Prerequisites and Instructions#

{
	"e2e": "cypress open", // Open the client and manually select execution
	"test": "cypress run && cypress run --component" // Execute all test cases in the command line
}

Tip

The API of cypress is written in a synchronous manner to execute asynchronously. For example, async await does not need to be explicitly declared, it can be called directly. For example, when getting an element, it will have a corresponding waiting time to process asynchronously.

Use Cases#

Go to a specific page#

cy.visit(url);

Get an element#

Selector matching#

// This matching method can refer to the behavior of querySelector
cy.get(selector);

Content matching#

// Content matching, the following statement will match elements that contain the text "hello"
cy.contain('hello');

Event invocation#

Basic events#

// Taking the click event as an example, other events can be triggered in the same way
cy.get(selector).click();

Complex events#

// In addition to triggering basic events, this method can also trigger events such as mousedown and mouseup to simulate complex user operations
cy.get(selector).trigger(eventName);

Content verification#

// This syntax is used to determine that the selected element should have the content "hello"
cy.get(selector).should('have.value', 'hello');

// Determine if the top value of the element is 10px
cy.get(selector).should('have.css', 'top').and('eq', '10px');

Combined with the syntax prompt of ts, the first parameter of should has many other behaviors for verification

Simulate keystrokes#

// Press and hold ctrl
cy.get('body').type('{ctrl}', { release: false });

// Release ctrl
cy.get('body').type('{ctrl}', { release: true });

API request#

Get the result of an API call#

// Start listening to an API
 cy.intercept({
    method: 'GET',
    // For example, to listen to /api/login?account=xxx, the syntax is: /api/login*
    url: `path of the API`, 
  }).as('test');

// Note: When the listening code starts executing, if the subsequent request behavior is not the one being listened to, an error will be reported. In other words, after starting to listen, you need to ensure that the subsequent requests are definitely the ones being listened to. Therefore, you cannot start listening at the beginning. The recommended approach is to start listening and immediately trigger a button click behavior to call the API.

// Get the request result of the API
cy.wait('@test')
	.its('response.body')
	.then(data => {
		cy.log(JSON.stringify(data));
	});

Based on the above description, the following method can be encapsulated and used

export const watchRequest = <T>(url: string, trigger: () => void, callback: (data: T) => void) => {
	cy.intercept({
		method: 'GET',
		url: `${url}*`,
	}).as(url);

	trigger();

	cy.wait(`@${url}`)
	.its('response.body')
	.then(data) => {
		callback(data);
	});
};
Determine if a certain page is accessed normally#

In the above scenario, make the following adjustments to roughly determine if a certain page is accessed normally.

/**
* A certain page can be accessed normally
* @param url Page address
* @param requestCount Determine how many requests the page initiated are normal
*/
export const normalVisit = (url: string, requestCount = 30) => {
	cy.intercept({
		url: '*',
	}).as('apiCheck')

	cy.visit(url);

	Array(requestCount).fill('').forEach(() => {
		cy.wait('@apiCheck').then((interception) => {
			expect(Boolean(interception.response)).equal(true);
			assert.isNotNull(interception.response!.body);
			expect(interception.response!.statusCode).to.be.oneOf([200, 304])
		});
	});
}

Modify request parameters#

// Modify the parameters of a GET request
 cy.intercept('/api/test*', (req) => {
	const request = JSON.parse(req.query as string);
	req.query.account = 2;
});

Note: The modified request parameters are not displayed in the console when viewing the request, but they have actually been changed.

Forced wait#

cy.wait(1000); // Wait for 1s

Custom Directives#

Check if an element exists#

Declare types#

/// <reference types="cypress" />
/// <reference types="cypress-wait-until" />

declare namespace Cypress {
	interface Chainable<Subject> {
		/**
		* Check if an element exists
		*
		* @param selector Selector
		* @return Chainable<Subject>
		*/
		isElementExist(selector: string): Chainable<Subject>;
	}
}

Define the directive#

/// <reference types="cypress" />
/// <reference types="cypress-wait-until" />

require("cypress-wait-until");

export function isElementExist(selector: string) {
	return cy
		.window()
		.then(($window) => $window.document.querySelector(selector));
}

Cypress.Commands.add("isElementExist", isElementExist);

Use the directive#

cy.isElementExist(".shoe-id").then((value) => {
	if (value) {
		// ...
	} else {
		// ...
	}
}

Test Data#

The json files in the cypress/fixtures directory can be used as test data. For example: user.json:

{
	"username": "hello world"
}

Then you can retrieve it like this when using it

cy.fixture('user').then(res => {
	console.log(res.username);
})
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.