I have a Cypress test that spies on the console log and expect it to be called with an object containing an array in 1 of its property and the test works but it's really strict and has to be exactly the same sort order but in some cases the order might vary and then my test fail even though the array members are what I want.
Cypress test
describe('My Test', () => {
beforeEach(() => {
// create a console.log spy for later use
cy.window().then((win) => {
cy.spy(win.console, "log");
});
});
it(`should expect console log to be called with an array in 1 of its member`, () => {
cy.get('.my-grid')
.find('.first-page')
.click()
.wait(10);
cy.window().then((win) => {
expect(win.console.log).to.be.calledWith("Grid State changed:: ", { newValues: { dataContextIds: [12, 13, 522, 1, 3] }, type: 'rowSelection' });
});
});
});
The problem as you can imagine is with the dataContextIds: [12, 13, 522, 1, 3], I would rather type in my code [1, 3, 12, 13, 522] without caring about the order but that fails in Cypress since it seems to be doing a strict assertion check.
I found this Chai issue but I'm not sure how to implement that in Cypress.
If I was to write this in Jest, I think it could be written in this way (didn't test it though, refered to this Jest article)
const unorderedArray = [12, 13, 522, 1, 3];
console.log("Grid State changed:: ", { newValues: { dataContextIds: unorderedArray }, type: 'rowSelection' });
expect(myArray).toHaveBeenCalledWith(
"Grid State changed:: ", {
newValues: expect.objectContaining({
dataContextIds: expect.arrayContaining([1, 3, 12, 13, 522])
})
}
);
How can I do that in Cypress? I don't care about the array order, I care about its content only. I don't want a strict equal, I want a loosely equal check.
This is a slightly different way of getting the window, but your way should work too.
describe('My Test', () => {
let called;
Cypress.on('window:before:load', win => {
// Stub instead of spying to make inspecting the calls easier:
cy.stub(win.console, 'log', msg => {
if (msg.newValues) {
called = true;
expect(msg.newValues.dataContextIds).to.include.members([1, 3, 12, 13, 522]);
}
});
});
beforeEach(() => {
// Reset calls to console log before each test
called = false;
});
it('test', () => {
// cy.get('.my-grid') ...
// Make sure that at least one message had the newValues property
// (using npm package cypress-wait-until):
cy.waitUntil(() => called, {
// This optional object example is taken from the docs (linked below)
errorMsg: 'This is a custom error message',
timeout: 2000, // waits up to 2000 ms, default to 5000
interval: 500 // performs the check every 500 ms, default to 200
})
});
});
The package used can be found at https://www.npmjs.com/package/cypress-wait-until
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With