39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
|
|
import { http, HttpResponse } from 'msw'
|
||
|
|
import { describe, expect, it } from 'vitest'
|
||
|
|
import { server } from '../test/server'
|
||
|
|
import { ApiError, api } from './api'
|
||
|
|
|
||
|
|
describe('api.postJson', () => {
|
||
|
|
it('sends application/json and returns the parsed body', async () => {
|
||
|
|
let sentContentType: string | null = null
|
||
|
|
|
||
|
|
server.use(
|
||
|
|
http.post('http://localhost/api/login', async ({ request }) => {
|
||
|
|
sentContentType = request.headers.get('Content-Type')
|
||
|
|
return HttpResponse.json({ id: 'u1', email: 'a@b.com' })
|
||
|
|
}),
|
||
|
|
)
|
||
|
|
|
||
|
|
const result = await api.postJson<{ id: string; email: string }>('/login', {
|
||
|
|
username: 'a@b.com',
|
||
|
|
password: 'secret',
|
||
|
|
})
|
||
|
|
|
||
|
|
expect(sentContentType).toBe('application/json')
|
||
|
|
expect(result).toEqual({ id: 'u1', email: 'a@b.com' })
|
||
|
|
})
|
||
|
|
|
||
|
|
it('throws ApiError on a non-2xx response', async () => {
|
||
|
|
server.use(
|
||
|
|
http.post('http://localhost/api/login', () =>
|
||
|
|
HttpResponse.json({ message: 'bad creds' }, { status: 401 }),
|
||
|
|
),
|
||
|
|
)
|
||
|
|
|
||
|
|
const error = await api.postJson('/login', {}).catch((e: unknown) => e)
|
||
|
|
|
||
|
|
expect(error).toBeInstanceOf(ApiError)
|
||
|
|
expect((error as ApiError).status).toBe(401)
|
||
|
|
})
|
||
|
|
})
|