Xunnamius/next-test-api-route-handler

Expose function callbacks to TestApiClient instance in next major version

Closed this issue ยท 2 comments

The solution

I think these test, requestPatcher and responsePatcher functions are unnecessary to be defined when creating tester instance. It's so limited when we need to create tester with some options dynamically and asynchronous work with Promises is better than callbacks. So, to avoid dirty codes caused by callbacks, it can be solved by exposing these functions like setting headers to be setted after the testApiHandler instance is created.

Example:

const api = require("../../pages/api/someApiEndpoint")
const { TestApiClient } = require("next-test-api-route-handler")

// as class instance:
const tester = new TestApiClient({ handler: api })
// as function:
const tester = TestApiClient({ handler: api })

// Proposal 1: defining directly
tester.request.headers = { key: process.env.SPECIAL_TOKEN }
// Proposal 2: exposing 'setXXX' functions 
tester.request.setHeader('key', process.env.SPECIAL_TOKEN)

const example = await tester.fetch({ method: 'GET' }).then(r => r.json())

// test with test environments like jest
expect(example).toBe('test')

// Block tentative after test was already executed
tester.request.setHeader('test', 'error')
// Error: cannot set header after test was already executed

Alternatives considered

I'm open to other suggestions, but if you dont want to expose everything because there are too many codes to be edited, you can only expose the test function and this will help me a lot.

Additional context

Interesting. What use case does this alternative interface solve more elegantly than the current Promise-based interface? Keep in mind the testApiHandler function is meant to be self-contained. Specifically, it:

  1. Spins up a mini-HTTP server listening on a unique port
  2. Uses it to run your handler function in a Next-like context (where Next internals create special request and response instances)
  3. Guarantees that small HTTP server spins down cleanly before the test ends regardless of what happens with your handler and test assertions

Seems like you want an interface that splits these steps up, and then adds some checks on the request and response objects Next creates, like with setHeader? I'm certainly open to a PR demonstrating this ๐Ÿ™‚

If you're just looking for just "the test function," if you mean Next's API resolver, you can see it here.

I had not considered the structure and mechanism of the project was to apply features of my issue. I was in a hurry to submit feedback ๐Ÿ˜….