Cypress: Unable to import mongodb module in cypress test

Created on 5 Dec 2018  路  6Comments  路  Source: cypress-io/cypress

Current behavior:

I am trying to import mongodb node module to update some status after the tests.
But cypress is thowing an exception and failing to start test.

mongodb import statment in cypress test

const MongoClient = require('mongodb').MongoClient

package.json

"dependencies": {
    "cypress": "^3.1.3",
    "mongodb": "^3.1.10",
  }

Note: I have noticed similar issue while importing "snowflake-sdk" also.


cypress-mongo-error

Desired behavior:

should be able to import 3rd party modules

Versions

all versions of cypress


macOS Highsierra. macOS Mojave

duplicate

Most helpful comment

Cypress serves your specs to the browser, they are not evaluated in node, but rather the browser.

You cannot import mongo adapter because it only works in node.

What you want to do is instead use cy.task(...) and in your pluginsFile write the implementation for each task. The pluginsFile is evaluated in node, rather than the browser, so you can do anything you want in there that you'd normally do in node.

All 6 comments

Cypress serves your specs to the browser, they are not evaluated in node, but rather the browser.

You cannot import mongo adapter because it only works in node.

What you want to do is instead use cy.task(...) and in your pluginsFile write the implementation for each task. The pluginsFile is evaluated in node, rather than the browser, so you can do anything you want in there that you'd normally do in node.

@brian-mann thank you so much for your quick response. I would use cy.task(...) as you explained.

Yes - please see this FAQ question on import/require also: https://on.cypress.io/using-cypress-faq#How-do-I-require-or-import-node-modules-in-Cypress

Link has changed. Is now:
https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-require-or-import-node-modules-in-Cypress

@a5g Thank you for your time in recording this video. It helped me a lot.

Was this page helpful?
0 / 5 - 0 ratings