I’m writing a cypress test for a webpage that shows a list of posts with filters on the top.
But for the list of posts to be shown, some documents have to be present in the Database so that I can check that they are displayed as required.
How can I add some documents in the test file, for example, say in the beforeEach()
function?
This is the code of posts-summary-test.ts
file:
describe('posts summary page', () => {
beforeEach(() => {
cy.visit('/postssummary');
cy.wait(2000);
});
it('posts must be displayed in descending order of posted time',() => {
cy.findByLabelText(.......
......
......
......
)};
)};
In this file, where can I add few documents to test the webpage?
4
Answers
It sounds like you’re looking for Cypress Fixtures.
It’s a way, where you can define some static information to test against. So instead of fetching it all the way from the database, then you can load your content on your site and check that it matches the information in your fixtures.
Be careful not to make what you’re testing ‘too big of an arc’, since that’ll make it harder to know what broke and how to solve it.
If you really want to load the contents from your database, to test directly against that, then I would suggest making a script that generates the fixtures. But I wouldn’t do that in Cypress.
There are several approaches possible:
before
handler, thus populating the database.cy.task
calling the code to populate your database, as described in the Cypress documentation or following this Cypress example code.There’s an example here bahmutov/cypress-example-mongodb
In
/cypress/plugins/index.js
add the task to clear the dbYou can try this plugin: https://www.npmjs.com/package/cypress-mongodb
It’s easy to setup, and gives you a list of commands to work with mongodb