I have some code that uses the local API, and I'd like to test it.
So I followed this tutorial: https://payloadcms.com/blog/typescript-jest-vscode-debugger-tutorial
The thing is, if I write this code:
const users = await payload.find({
collection: 'users'
});
expect(users).toBeDefined();
I get the following error: Cannot read properties of undefined (reading 'collections')
According to this discussion, it's due to the fact that payload is initialized in a different process than the one in which the test is executed.
My question is, is there any way to configure payload so my test works ?
(additionally, I have some problem with the database, since I need it to be populated in order to run my test.)
Hey @MattRvt , we do testing like this within Payload's test suite. That would probably be a good place to start. The high-level idea is that you'll need to call payload.init
within your test suite before making any calls via the local API.
For example, looking at our access-control test suite:
beforeAll
block that calls a helper function - linkpayload.init
internally - linkData seeding can either be done within a jest block or done via the onInit config function
That's what I saw in the repository, but I was afraid it was an oversized solution. But if it's the best one, I'll use it.
My test DB contains about 100 entries. So I'm looking for a way to import them all at once.
To fill the DB, it is not possible to use a dump (created with mongodump) as mongodb-memory-server does not allow to do it directly, but maybe there is another solution.
I will try to export my database in JSON and then import it using the method you describe, but it doesn't seem to be an ideal solution.
Payload will automatically attempt to use mongodb-memory-server if two conditions are met:
- It is locally installed in your project
- NODE_ENV is equal to test
So, I simply uninstall mongodb-memory-server
and Payload is still trying to use mongodb-memory-server
I will try to export my database in JSON and then import it using the method you describe, but it doesn't seem to be an ideal solution.
Thank you for your help
Star
Discord
online
Get dedicated engineering support directly from the Payload team.