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.
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
- 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
- This example uses the following folder structure:
root
└─ /src
└─ payload.config.ts
└─ /tests
- Add test credentials to your project. Create a file at
src/tests/credentials.tswith the following contents:
export default {
email: 'test@test.com',
password: 'test',
}
- 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.tswith 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
- Add a
jest.config.tsfile 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',
},
},
],
},
}
- Write your first test. Create a file at
src/tests/login.spec.tswith 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()
})
})
- Add a script to run tests via the command line. Add the following to your
package.jsonscripts:
"scripts": {
"test": "jest --forceExit --detectOpenHandles"
}
- Run your tests:
yarn test