├── .npmrc ├── jest.config.js ├── index.d.ts ├── index.js ├── .github └── workflows │ ├── tests.yml │ └── release.yml ├── LICENSE ├── package.json ├── .gitignore ├── index.test.js └── README.md /.npmrc: -------------------------------------------------------------------------------- 1 | strict-peer-dependencies=false 2 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('@jest/types').Config.InitialOptions} */ 2 | module.exports = { 3 | coverageProvider: "v8", 4 | }; 5 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export declare const createMocks: any; 2 | /** 3 | * Parse the response 4 | * 5 | * @param {Object} response 6 | * @return {{headers: Headers, body: any, statusCode: number}} 7 | */ 8 | export declare function parseResponse(response: any): { 9 | statusCode: any; 10 | headers: any; 11 | body: any; 12 | json: () => any; 13 | }; 14 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const {createMocks} = require('node-mocks-http'); 2 | 3 | /** 4 | * Parse the response 5 | * 6 | * @param {Object} response 7 | * @return {{headers: Headers, body: any, statusCode: number}} 8 | */ 9 | function parseResponse(response) { 10 | const {statusCode, _getHeaders, _getData} = response; 11 | return { 12 | statusCode, 13 | headers: _getHeaders(), 14 | body: _getData(), 15 | json: () => JSON.parse(_getData()), 16 | }; 17 | } 18 | 19 | module.exports = { 20 | createMocks, 21 | parseResponse, 22 | }; 23 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | strategy: 15 | matrix: 16 | node-version: [ 14.x, 16.x, 18.x ] 17 | 18 | steps: 19 | - uses: actions/checkout@v3 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | cache: 'npm' 25 | - run: npm ci 26 | - run: npm run build --if-present 27 | - run: npm test 28 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Release 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-node@v3 13 | with: 14 | node-version: 16 15 | - run: npm ci 16 | - run: npm test 17 | 18 | publish-npm: 19 | needs: build 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v3 23 | - uses: actions/setup-node@v3 24 | with: 25 | node-version: 18 26 | registry-url: https://registry.npmjs.org/ 27 | - run: npm ci 28 | - run: npm publish 29 | env: 30 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Shahrad Elahi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "next-test-api-routes", 3 | "version": "0.0.2", 4 | "description": "A Lightweight library for testing Next.js API routes", 5 | "author": "Shahrad Elahi ", 6 | "license": "MIT", 7 | "repository": "https://github.com/shahradelahi/next-test-api-routes.git", 8 | "main": "index.js", 9 | "types": "index.d.ts", 10 | "scripts": { 11 | "test": "jest", 12 | "test:watch": "jest --watch" 13 | }, 14 | "devDependencies": { 15 | "@jest/globals": "^29.3.1", 16 | "jest": "^29.3.1" 17 | }, 18 | "dependencies": { 19 | "node-mocks-http": "^1.12.1" 20 | }, 21 | "keywords": [ 22 | "next", 23 | "nextjs", 24 | "api", 25 | "routes", 26 | "testing", 27 | "jest", 28 | "test" 29 | ], 30 | "files": [ 31 | "index.js", 32 | "index.d.ts" 33 | ], 34 | "publishConfig": { 35 | "access": "public" 36 | }, 37 | "bugs": { 38 | "url": "https://github.com/shahradelahi/next-test-api-routes/issues", 39 | "email": "opensource@litehex.com" 40 | }, 41 | "homepage": "https://github.com/shahradelahi/next-test-api-routes", 42 | "readme": "README.md" 43 | } 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | # JetBrains WebStorm 107 | .idea/ 108 | -------------------------------------------------------------------------------- /index.test.js: -------------------------------------------------------------------------------- 1 | const {describe, expect, test} = require('@jest/globals'); 2 | const {createMocks, parseResponse} = require('./index'); 3 | 4 | const helloRoute = async (req, res) => res.status(200).json({message: 'Hello World'}); 5 | 6 | const echoRoute = async (req, res) => { 7 | if (req.method !== 'POST') { 8 | return res.status(200).json({error: 'Only POST requests are allowed'}); 9 | } 10 | if (!req.body.message) { 11 | return res.status(200).json({error: 'No message provided'}); 12 | } 13 | return res.status(200).json({message: req.body.message}); 14 | } 15 | 16 | describe("Test the hello route", () => { 17 | test("It should respond with a 200 status code", async () => { 18 | const {req, res} = createMocks({ 19 | method: 'GET', 20 | url: '/hello', 21 | }); 22 | const resp = parseResponse(await helloRoute(req, res)); 23 | expect(resp.statusCode).toBe(200); 24 | }); 25 | test("It should respond with a JSON object", async () => { 26 | const {req, res} = createMocks({ 27 | method: 'GET', 28 | url: '/hello', 29 | }); 30 | const resp = parseResponse(await helloRoute(req, res)); 31 | expect(resp.headers['content-type']).toBe('application/json'); 32 | }); 33 | test("It should respond with a message", async () => { 34 | const {req, res} = createMocks({ 35 | method: 'GET', 36 | url: '/hello', 37 | }); 38 | const resp = parseResponse(await helloRoute(req, res)); 39 | expect(resp.json().message).toBe('Hello World'); 40 | }); 41 | }); 42 | 43 | describe("Test the echo route", () => { 44 | test("It should send an error if the method is not POST", async () => { 45 | const {req, res} = createMocks({ 46 | method: 'GET', 47 | url: '/echo', 48 | }); 49 | const resp = parseResponse(await echoRoute(req, res)); 50 | expect(resp.json().error).toBe('Only POST requests are allowed'); 51 | }); 52 | test("It should send an error if no message is provided", async () => { 53 | const {req, res} = createMocks({ 54 | method: 'POST', 55 | url: '/echo', 56 | }); 57 | const resp = parseResponse(await echoRoute(req, res)); 58 | expect(resp.json().error).toBe('No message provided'); 59 | }); 60 | test("It should send the message if it is provided", async () => { 61 | const {req, res} = createMocks({ 62 | method: 'POST', 63 | url: '/echo', 64 | body: { 65 | message: 'Hello World', 66 | }, 67 | }); 68 | const resp = parseResponse(await echoRoute(req, res)); 69 | expect(resp.json().message).toBe('Hello World'); 70 | }); 71 | }); 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⚡️ Next Test API Routes 2 | 3 | [![Tests](https://github.com/shahradelahi/next-test-api-routes/actions/workflows/tests.yml/badge.svg)](https://github.com/shahradelahi/next-test-api-routes/actions/workflows/tests.yml) 4 | [![npm version](https://badge.fury.io/js/next-test-api-routes.svg)](https://badge.fury.io/js/next-test-api-routes) 5 | [![npm](https://img.shields.io/npm/dt/next-test-api-routes)](https://www.npmjs.com/package/next-test-api-routes) 6 | 7 | ## Installation 8 | 9 | ```bash 10 | npm install --save-dev next-test-api-routes 11 | ``` 12 | 13 | ## Usage 14 | 15 | ```js 16 | import {createMocks, parseResponse} from 'next-test-api-routes' 17 | 18 | const route = require('./api/hello') 19 | 20 | describe('api/hello', () => { 21 | it('should return a 200 status code', async () => { 22 | const {req, res} = createMocks({ 23 | method: 'GET', 24 | }) 25 | 26 | const resp = parseResponse(await route(req, res)) 27 | 28 | expect(res.statusCode).toBe(200) 29 | }) 30 | 31 | it('should return a JSON object', async () => { 32 | const {req, res} = createMocks({ 33 | method: 'POST', 34 | body: { 35 | name: 'John Doe', 36 | }, 37 | }) 38 | 39 | const resp = parseResponse(await route(req, res)) 40 | 41 | expect(resp.json().message).toBe('Hello John Doe') 42 | }) 43 | }) 44 | ``` 45 | 46 | ## Methods 47 | 48 | ### createMocks 49 | 50 | Creates a mock request and response object. 51 | 52 | #### Parameters 53 | 54 | - `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** 55 | - `options.method` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** (optional, default `'GET'`) 56 | - `options.body` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** (optional, default `undefined`) 57 | - `options.query` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** (optional, default `{}`) 58 | - `options.headers` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** (optional, default `{}`) 59 | - `options.cookies` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** (optional, default `{}`) 60 | - `options.url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** (optional, default `/`) 61 | - `options.params` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** (optional, default `{}`) 62 | 63 | #### Examples 64 | 65 | ```js 66 | const {req, res} = createMocks({ 67 | method: 'GET', 68 | body: { 69 | name: 'John Doe', 70 | }, 71 | query: { 72 | page: 1, 73 | } 74 | }) 75 | ``` 76 | 77 | ### parseResponse 78 | 79 | Parses the response object from the route handler. 80 | 81 | #### Parameters 82 | 83 | - `response` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** 84 | 85 | #### Returns 86 | 87 | - `response` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** 88 | - `response.json` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Returns the parsed JSON object. 89 | - `response.body` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The response body as a string. 90 | - `response.headers` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** The response headers. 91 | - `response.statusCode` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The response status code. 92 | 93 | #### Examples 94 | 95 | ```js 96 | const {req, res} = createMocks({ 97 | method: 'GET', 98 | }) 99 | 100 | const resp = parseResponse(await route(req, res)) 101 | 102 | expect(resp.json().message).toBe('Hello World') 103 | ``` 104 | 105 | ## License 106 | 107 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details 108 | --------------------------------------------------------------------------------