Solution Review: Write a Test and Custom Command
Explore how to write effective Cypress tests and create custom commands to improve front-end testing workflows. Learn to intercept network requests, validate responses, and integrate commands for signing up users and posting articles. This lesson helps you build reusable test code for robust UI testing.
We'll cover the following...
We'll cover the following...
Solution
Note: You can see the Cypress UI better by opening the link next to Your app can be found at:
Cypress.Commands.add("createPost", ({ title, text } = {}) => {
cy.intercept("POST", "**/api/articles").as("create-article-request");
cy.visit("/editor");
cy.findByPlaceholderText("Article Title").type(title)
cy.findByPlaceholderText("Write your article (in markdown)").type(text)
cy.findByText("Publish Article").click()
// ... and AJAX call waiting
cy.wait("@create-article-request").should((interception) => {
expect(interception.request.body).deep.equal({
article: {
title,
body: text,
description: "",
tagList: []
},
});
expect(interception.response.statusCode).to.equal(200);
cy.wrap(interception.response.body)
.should("have.property", "article")
.and(article => expect(article).to.have.property("slug").and.to.be.a("string").and.not.to.be.empty)
.and("deep.include", { title, body: text });
});
});
context("Login flow", () => {
it("When the user is not registered, the server should respond with a 422 status", () => {
cy.signupV3();
cy.createPost({title: "title", text: "text"});
});
});
Explanation
Let’s learn the code line by line to understand how the command and tests work.