run test on local API

default discord avatar
MattRvtlast year
1 2

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.)

  • Selected Answer
    discord user avatar
    denolfe
    last year

    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:

    • There is a beforeAll block that calls a helper function - link
    • The helper function calls payload.init internally - link

    Data seeding can either be done within a jest block or done via the onInit config function

  • default discord avatar
    MattRvtlast year

    Payload init

    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.

    DB init

    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.

    Is it possible to use my local DB?

    Payload will automatically attempt to use mongodb-memory-server if two conditions are met:

    1. It is locally installed in your project
    2. 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 on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.