chore: passing localization int tests

This commit is contained in:
Jarrod Flesch
2024-02-16 23:22:01 -05:00
parent 28dc5a5b8c
commit 3d99ea5cbf
3 changed files with 94 additions and 64 deletions

View File

@@ -12,11 +12,14 @@ import {
PATCH as createPATCH,
POST as createPOST,
} from '../../packages/next/src/routes/rest'
import { devUser } from '../credentials'
type ValidPath = `/${string}`
type RequestQuery = {
query?: {
fallbackLocale?: string
limit?: number
locale?: string
page?: number
sort?: string
where?: Where
@@ -115,11 +118,13 @@ export class NextRESTClient {
return this._GET(request, { params: { slug } })
}
async GRAPHQL_POST(options: RequestInit): Promise<Response> {
async GRAPHQL_POST(options: RequestInit & RequestQuery): Promise<Response> {
const { query, ...rest } = options
const queryParams = generateQueryString(query, {})
const request = new Request(
`${this.serverURL}${this.config.routes.api}${this.config.routes.graphQL}`,
`${this.serverURL}${this.config.routes.api}${this.config.routes.graphQL}${queryParams}`,
{
...options,
...rest,
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
@@ -160,4 +165,21 @@ export class NextRESTClient {
})
return this._POST(request, { params: { slug } })
}
async login({
slug,
credentials,
}: {
credentials?: {
email: string
password: string
}
slug: string
}): Promise<Response> {
return this.POST(`/${slug}/login`, {
body: JSON.stringify(
credentials ? { ...credentials } : { email: devUser.email, password: devUser.password },
),
})
}
}

View File

@@ -1,13 +1,10 @@
import { GraphQLClient } from 'graphql-request'
import type { Config } from '../../packages/payload/src/config/types'
import type { Payload } from '../../packages/payload/src'
import type { Where } from '../../packages/payload/src/types'
import type { LocalizedPost, WithLocalizedRelationship } from './payload-types'
import payload from '../../packages/payload/src'
import { devUser } from '../credentials'
import { initPayloadTest } from '../helpers/configHelpers'
import { RESTClient } from '../helpers/rest'
import { getPayload } from '../../packages/payload/src'
import { NextRESTClient } from '../helpers/NextRESTClient'
import { startMemoryDB } from '../startMemoryDB'
import { arrayCollectionSlug } from './collections/Array'
import configPromise from './config'
import {
@@ -26,27 +23,17 @@ import {
} from './shared'
const collection = localizedPostsSlug
let config: Config
let client: RESTClient
let serverURL
let payload: Payload
let restClient: NextRESTClient
describe('Localization', () => {
let post1: LocalizedPost
let postWithLocalizedData: LocalizedPost
beforeAll(async () => {
;({ serverURL } = await initPayloadTest({ __dirname, init: { local: false } }))
client = new RESTClient(config, { serverURL, defaultSlug: collection })
await client.create({
data: {
email: devUser.email,
password: devUser.password,
},
})
await client.login()
config = await configPromise
const config = await startMemoryDB(configPromise)
payload = await getPayload({ config })
restClient = new NextRESTClient(payload.config)
// @ts-expect-error Force typing
post1 = await payload.create({
@@ -604,9 +591,6 @@ describe('Localization', () => {
let token
it('should allow user to login and retrieve populated localized field', async () => {
const url = `${serverURL}${config?.routes?.api}${config?.routes?.graphQL}?locale=en`
const client = new GraphQLClient(url)
const query = `mutation {
loginUser(email: "dev@payloadcms.com", password: "test") {
token
@@ -618,8 +602,13 @@ describe('Localization', () => {
}
}`
const response = await client.request(query)
const result = response.loginUser
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
query: { locale: 'en' },
})
.then((res) => res.json())
const result = data.loginUser
expect(typeof result.token).toStrictEqual('string')
expect(typeof result.user.relation.title).toStrictEqual('string')
@@ -628,10 +617,6 @@ describe('Localization', () => {
})
it('should allow retrieval of populated localized fields within meUser', async () => {
// Defining locale=en in graphQL string should not break JWT strategy
const url = `${serverURL}${config?.routes?.api}${config?.routes?.graphQL}?locale=en`
const client = new GraphQLClient(url)
const query = `query {
meUser {
user {
@@ -643,19 +628,21 @@ describe('Localization', () => {
}
}`
const response = await client.request(query, null, {
Authorization: `JWT ${token}`,
})
const result = response.meUser
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
query: { locale: 'en' },
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
const result = data.meUser
expect(typeof result.user.relation.title).toStrictEqual('string')
})
it('should create and update collections', async () => {
const url = `${serverURL}${config?.routes?.api}${config?.routes?.graphQL}`
const client = new GraphQLClient(url)
const create = `mutation {
createLocalizedPost(
data: {
@@ -668,9 +655,16 @@ describe('Localization', () => {
}
}`
const { createLocalizedPost: createResult } = await client.request(create, null, {
Authorization: `JWT ${token}`,
})
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query: create }),
query: { locale: 'en' },
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
const createResult = data.createLocalizedPost
const update = `mutation {
updateLocalizedPost(
@@ -684,9 +678,16 @@ describe('Localization', () => {
}
}`
const { updateLocalizedPost: updateResult } = await client.request(update, null, {
Authorization: `JWT ${token}`,
})
const { data: updateData } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query: update }),
query: { locale: 'en' },
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
const updateResult = updateData.updateLocalizedPost
const result = await payload.findByID({
collection: localizedPostsSlug,
@@ -782,27 +783,33 @@ describe('Localization', () => {
},
})
const { result: relationshipRes } = await client.find({
auth: true,
query: {
children: {
in: post1.id,
const { docs: relationshipDocs } = await restClient
.GET(`/${collection}`, {
query: {
where: {
children: {
in: post1.id,
},
},
},
},
})
})
.then((res) => res.json())
expect(relationshipRes.docs.map(({ id }) => id)).toContain(post1.id)
expect(relationshipDocs.map(({ id }) => id)).toContain(post1.id)
const { result: nestedFieldRes } = await client.find({
auth: true,
query: {
'group.children': {
contains: 'some',
const { docs: nestedFieldDocs } = await restClient
.GET(`/${collection}`, {
query: {
where: {
'group.children': {
contains: 'some',
},
},
},
},
})
})
.then((res) => res.json())
expect(nestedFieldRes.docs.map(({ id }) => id)).toContain(post1.id)
expect(nestedFieldDocs.map(({ id }) => id)).toContain(post1.id)
})
})
})

View File

@@ -13,3 +13,4 @@ export const localizedPostsSlug = 'localized-posts'
export const withLocalizedRelSlug = 'with-localized-relationship'
export const relationshipLocalizedSlug = 'relationship-localized'
export const withRequiredLocalizedFields = 'localized-required'
export const usersSlug = 'users'