Hi. I am trying to connect to Mongo Atlas using Nextjs (^13.5.3), mongodb (^6.1.0) and nodejs (20.5.1). My web app is running perfectly, retrieves and updates data as it should. However when I run my tests with Jest and React Tesing Library, the following error is logged:
TypeError: Cannot read properties of undefined (reading 'startsWith')
7 |
8 | // Create a MongoClient with a MongoClientOptions object to set the Stable API version
> 9 | const client = new MongoClient(uri as string, {
| ^
10 | serverApi: {
11 | version: ServerApiVersion.v1,
12 | strict: false,
at connectionStringHasValidScheme (node_modules/mongodb-connection-string-url/src/index.ts:13:22)
at new ConnectionString (node_modules/mongodb-connection-string-url/src/index.ts:132:30)
at parseOptions (node_modules/mongodb/src/connection_string.ts:244:15)
at new MongoClient (node_modules/mongodb/src/mongo_client.ts:331:34)
at Object.<anonymous> (src/data/mongodb.ts:9:16)
at Object.<anonymous> (src/components/Sidebar/Sidebar.tsx:12:18)
at Object.<anonymous> (src/components/Sidebar/__test__/Sidebar.test.tsx:8:57)
I read a same issue related to this: TypeError: Cannot read property 'startsWith' of undefined
The problem was solved by moving the .env files inside the source directory, but that also didn’t work for me.
At this point, I have no idea what could be the problem. My only thought is that the node server isn’t running when I run the tests so the enviroment variables can’t be accessed. But I need to include the Sidebar component so I could test it in the unit test.
Here is the code that throws the error:
const uri = process.env.MONGODB_CONNECTION_STRING;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri as string, {
serverApi: {
version: ServerApiVersion.v1,
strict: false,
deprecationErrors: true,
},
});
Appreciate every help ![]()
