Cypress component test to assert function called with deep nested object value
When doing cypress component test on a form, I came across an issue that the onSubmit
function is called with a deep nested object. The object looks something like this:
{
relationshipPartner: {
id: string;
email: string;
info: { firstName: string; lastName:string; }
};
...moreProperties,
}
I wanted to assert that onSubmit
function is called with the correct relationship partner email. It was really hard to use .toEqual()
. When I had the order of the properties wrong it returns false
and I always had to write out the whole object even when I only care about the relationship partner email.
It was quite a struggle but in the end I had a solution looks like this:
it("should submit with relationship partner", () => {
const onSubmit = cy.stub().as("onSubmit");
mount(
<AddCompanyRelationshipPartner
onSubmit={onSubmit}
/>
);
cy.findByRole("button", { name: /Update Relationship Partner/i }).click();
cy.findAllByLabelText(/relationship partner/i)
.first()
.type("ellen{enter}");
cy.findByRole("button", { name: /Save/i }).click();
cy.get("@onSubmit").should((i) => {
const spy = i["getCalls"]();
const { args } = spy[0];
expect(args[0].relationshipPartner.email).to.equal("ellen@nexl.io");
});
});
Hope this helps =)