Files
payload/examples/testing
Alessio Gravili 13fc94dc4d chore: upgrade to TypeScript 5.7, ensure tsconfig targed and lib properties match the APIs we support (#9473)
TS 5.7 added support for ES2024. By keeping target: “esnext”, we would
have accidentally set our minimum supported ES version to ES2024.

This sets it to ES2022, which is the version supported by Node 18
2024-11-23 16:35:27 -07:00
..
2024-08-13 12:54:33 -04: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.

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