The correct way to test custom resolver #1253
-
I've created some custom response resolver export const withBearerAuthorization = (resolver) => {
return (req, res, ctx) => {
const authorization = req.headers.get("authorization")
if (!authorization || !authorization.startsWith("Bearer "))
return res(
ctx.status(200),
ctx.json({
msg: "Missing Authorization Header"
})
)
return resolver(req, res, ctx)
}
} and test it like this const stubResolver = (req, res, ctx) => res(
ctx.status(200)
)
describe("withBearerAuthorization tests", () => {
test("Request without authorization header", async () => {
const requestWithoutAuthHeader = new Request('/some_url')
const result = await withBearerAuthorization(stubResolver)(requestWithoutAuthHeader, response, context)
// Result has the following format:
// {
// status: 401, // Number
// body: "{"msg":"Missing Authorization Header"}" // String
// ... // other properties
// }
expect(result).toHaveProperty('status', 200)
expect(result).toHaveProperty('body')
expect(result.body).toStrictEqual(JSON.stringify({
msg: "Missing Authorization Header"
}))
})
}) My question may seem a little strange, but I'm looking for a better approach: Is this the correct way to test custom resolver, or is there a better approach for testing it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi, @evgenoir. That's a perfect question, thanks for raising this. Overall, your testing direction is solid. I will try adding a few points below.
|
Beta Was this translation helpful? Give feedback.
Hi, @evgenoir. That's a perfect question, thanks for raising this.
Overall, your testing direction is solid. I will try adding a few points below.
Request
vsMockedRequest
I like that you construct a plain
Request
instance to pass as thereq
argument. But, strictly speaking, thereq
we construct in MSW is not a 1-1 equivalent of the fetch'sRequest
, as the library's one has extra properties (likepassthrough()
orparams
). You may run into some issues as you're passing in not what MSW would produce on its own.We currently don't expose the means to construct a
MockedRequest
instance publicly as we treat that instance as an implementation detail of the library. For testing purposes internal…