Files
payloadcms/examples/testing
Sasha 6b4842d44d feat(cpa): create project from example using --example CLI arg (#10172)
Adds the ability to create a project using an existing in the Payload
repo example through `create-payload-app`:

For example:
`pnpx create-payload-app --example custom-server` - creates a project
from the
[custom-server](https://github.com/payloadcms/payload/tree/main/examples/custom-server)
example.

This is much easier and faster then downloading the whole repo and
copying the example to another folder.
Note that we don't configure the payload config with the storage / DB
adapter there because examples can be very specific.
2024-12-27 20:16:34 +02:00
..
2024-02-28 13:44:17 -05:00

Payload Testing Example

This example demonstrates how to get started with testing Payload using Jest. You can clone this down and use it as a starting point for your own Payload projects, or you can follow the steps below to add testing to your existing Payload project.

Spin up locally:

Run the following command to create a project from the example:

  • npx create-payload-app --example testing

Add testing to your existing Payload project

  1. Initial setup:
# install dependencies
yarn add --dev jest mongodb-memory-server @swc/jest @swc/core isomorphic-fetch @types/jest
# create a .env file
cp .env.example .env
  1. This example uses the following folder structure:
root
└─ /src
    └─ payload.config.ts
    └─ /tests
  1. Add test credentials to your project. Create a file at src/tests/credentials.ts with the following contents:
export default {
  email: 'test@test.com',
  password: 'test',
}
  1. Add the global setup file to your project. This file will be run before any tests are run. It will start a MongoDB server and create a Payload instance for you to use in your tests. Create a file at src/tests/globalSetup.ts with the following contents:
import { resolve } from 'path'
import payload from 'payload'
import express from 'express'
import testCredentials from './credentials'

require('dotenv').config({
  path: resolve(__dirname, '../../.env'),
})

const app = express()

const globalSetup = async () => {
  await payload.init({
    secret: process.env.PAYLOAD_SECRET_KEY,
    express: app,
  })

  app.listen(process.env.PORT, async () => {
    console.log(`Express is now listening for incoming connections on port ${process.env.PORT}.`)
  })

  const response = await fetch(
    `${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/first-register`,
    {
      body: JSON.stringify({
        email: testCredentials.email,
        password: testCredentials.password,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'post',
    },
  )

  const data = await response.json()

  if (!data.user || !data.user.token) {
    throw new Error('Failed to register first user')
  }
}

export default globalSetup
  1. Add a jest.config.ts file to the root of your project:
module.exports = {
  verbose: true,
  globalSetup: '<rootDir>/src/tests/globalSetup.ts',
  roots: ['<rootDir>/src/'],
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
  transform: {
    '^.+\\.(t|j)sx?$': [
      '@swc/jest',
      {
        jsc: {
          target: 'es2021',
        },
      },
    ],
  },
}
  1. Write your first test. Create a file at src/tests/login.spec.ts with the following contents:
import { User } from '../payload-types'
import testCredentials from './credentials'

describe('Users', () => {
  it('should allow a user to log in', async () => {
    const result: {
      token: string
      user: User
    } = await fetch(`${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/login`, {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: testCredentials.email,
        password: testCredentials.password,
      }),
    }).then((res) => res.json())

    expect(result.token).toBeDefined()
  })
})
  1. Add a script to run tests via the command line. Add the following to your package.json scripts:
"scripts": {
  "test": "jest --forceExit --detectOpenHandles"
}
  1. Run your tests:
yarn test