Home > database >  How add documents into a MongoDb database in a cypress test file?
How add documents into a MongoDb database in a cypress test file?

Time:05-24

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?

CodePudding user response:

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.

CodePudding user response:

There are several approaches possible:

  1. If the tested application has an API for adding posts, you could call this API in the before handler, thus populating the database.
  2. Use cy.task calling the code to populate your database, as described in the Cypress documentation or following this Cypress example code.
  3. When your tests are running in a pipeline, such as provided by Azure DevOps or Jenkins, you could add a database setup step, using whatever technology you like, so you're not limited to the Node execution environment.
  • Related