next-test-api-routes
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

⚡️ Next Test API Routes

Tests npm version npm

Installation

npm install --save-dev next-test-api-routes 

Usage

import {createMocks, parseResponse} from 'next-test-api-routes'

const route = require('./api/hello')

describe('api/hello', () => {
   it('should return a 200 status code', async () => {
      const {req, res} = createMocks({
         method: 'GET',
      })

      const resp = parseResponse(await route(req, res))

      expect(res.statusCode).toBe(200)
   })

   it('should return a JSON object', async () => {
      const {req, res} = createMocks({
         method: 'POST',
         body: {
            name: 'John Doe',
         },
      })

      const resp = parseResponse(await route(req, res))

      expect(resp.json().message).toBe('Hello John Doe')
   })
})

Methods

createMocks

Creates a mock request and response object.

Parameters

  • options Object
    • options.method string (optional, default 'GET')
    • options.body Object (optional, default undefined)
    • options.query Object (optional, default {})
    • options.headers Object (optional, default {})
    • options.cookies Object (optional, default {})
    • options.url string (optional, default /)
    • options.params Object (optional, default {})

Examples

const {req, res} = createMocks({
   method: 'GET',
    body: {
        name: 'John Doe',
    },
    query: {
        page: 1,
    }
})

parseResponse

Parses the response object from the route handler.

Parameters

Returns

  • response Object
  • response.json Function Returns the parsed JSON object.
  • response.body string The response body as a string.
  • response.headers Object The response headers.
  • response.statusCode number The response status code.

Examples

const {req, res} = createMocks({
   method: 'GET',
})

const resp = parseResponse(await route(req, res))

expect(resp.json().message).toBe('Hello World')

License

This project is licensed under the MIT License - see the LICENSE file for details

Package Sidebar

Install

npm i next-test-api-routes

Weekly Downloads

1

Version

0.0.2

License

MIT

Unpacked Size

6.57 kB

Total Files

5

Last publish

Collaborators

  • shahradelahi