1 import { Prerequisites, CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Example: Write Integration Tests for API Routes`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn how to write integration tests for API routes using [medusaIntegrationTestRunner](../page.mdx) from Medusa's Testing Framework.
10
11 <Prerequisites
12 items={[
13 {
14 text: "Testing Tools Setup",
15 link: "/learn/debugging-and-testing/testing-tools"
16 }
17 ]}
18 />
19
20 ## Test a GET API Route
21
22 Consider the following API route created at `src/api/custom/route.ts`:
23
24 ```ts title="src/api/custom/route.ts"
25 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
26
27 export async function GET(
28 req: MedusaRequest,
29 res: MedusaResponse
30 ){
31 res.json({
32 message: "Hello, World!",
33 })
34 }
35 ```
36
37 To write an integration test that tests this API route, create the file `integration-tests/http/custom-routes.spec.ts` with the following content:
38
39 export const getHighlights = [
40 ["8", "api.get", "Send a GET request to the `/custom` API route."]
41 ]
42
43 ```ts title="integration-tests/http/custom-routes.spec.ts" highlights={getHighlights}
44 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
45
46 medusaIntegrationTestRunner({
47 testSuite: ({ api, getContainer }) => {
48 describe("Custom endpoints", () => {
49 describe("GET /custom", () => {
50 it("returns correct message", async () => {
51 const response = await api.get(
52 `/custom`
53 )
54
55 expect(response.status).toEqual(200)
56 expect(response.data).toHaveProperty("message")
57 expect(response.data.message).toEqual("Hello, World!")
58 })
59 })
60 })
61 },
62 })
63
64 jest.setTimeout(60 * 1000)
65 ```
66
67 You use the `medusaIntegrationTestRunner` to write your tests.
68
69 You add a single test that sends a `GET` request to `/custom` using the `api.get` method. For the test to pass, the response is expected to:
70
71 - Have a code status `200`,
72 - Have a `message` property in the returned data.
73 - Have the value of the `message` property equal to `Hello, World!`.
74
75 ### Run Tests
76
77 Run the following command to run your tests:
78
79 ```bash npm2yarn
80 npm run test:integration:http
81 ```
82
83 <Note title="Tip">
84
85 If you don't have a `test:integration:http` script in `package.json`, refer to the [Medusa Testing Tools chapter](../../page.mdx#add-test-commands).
86
87 </Note>
88
89 This runs your Medusa application and runs the tests available under the `src/integrations/http` directory.
90
91 ### Jest Timeout
92
93 Since your tests connect to the database and perform actions that require more time than the typical tests, make sure to increase the timeout in your test:
94
95 ```ts title="integration-tests/http/custom-routes.spec.ts"
96 // in your test's file
97 jest.setTimeout(60 * 1000)
98 ```
99
100 ---
101
102 ## Test a POST API Route
103
104 Suppose you have a `blog` module whose main service extends the service factory, and that has the following model:
105
106 ```ts title="src/modules/blog/models/my-custom.ts"
107 import { model } from "@medusajs/framework/utils"
108
109 const Post = model.define("post", {
110 id: model.id().primaryKey(),
111 name: model.text(),
112 })
113
114 export default Post
115 ```
116
117 And consider that the file `src/api/custom/route.ts` defines another route handler for `POST` requests:
118
119 ```ts title="src/api/custom/route.ts"
120 // other imports...
121 import createPostWorkflow from "../../workflows/create-post"
122
123 // ...
124
125 export async function POST(
126 req: MedusaRequest,
127 res: MedusaResponse
128 ) {
129 const { result: post } = await createPostWorkflow(req.scope)
130 .run({
131 input: req.body,
132 })
133
134 res.json({
135 post,
136 })
137 }
138 ```
139
140 This API route executes a `createPostWorkflow` workflow that creates a new record of `Post`. The workflow's implementation isn't shown here, as it isn't relevant to writing the test. Learn how to create a workflow in the [Workflows](../../../../fundamentals/workflows/page.mdx) chapter.
141
142 To write tests for this API route, add the following at the end of the `testSuite` function in `integration-tests/http/custom-routes.spec.ts`:
143
144 export const postHighlights = [
145 ["14", "api.post", "Send a POST request to the `/custom` API route."]
146 ]
147
148 ```ts title="integration-tests/http/custom-routes.spec.ts" highlights={postHighlights}
149 // other imports...
150 import BlogModuleService from "../../src/modules/blog/service"
151
152 medusaIntegrationTestRunner({
153 testSuite: ({ api, getContainer }) => {
154 describe("Custom endpoints", () => {
155 // other tests...
156
157 describe("POST /custom", () => {
158 const id = "1"
159
160 it("Creates my custom", async () => {
161
162 const response = await api.post(
163 `/custom`,
164 {
165 id,
166 name: "Test",
167 }
168 )
169
170 expect(response.status).toEqual(200)
171 expect(response.data).toHaveProperty("post")
172 expect(response.data.post).toEqual({
173 id,
174 name: "Test",
175 created_at: expect.any(String),
176 updated_at: expect.any(String),
177 })
178 })
179 })
180 })
181 },
182 })
183 ```
184
185 This adds a test for the `POST /custom` API route. It uses `api.post` to send the POST request. The `api.post` method accepts as a second parameter the data to pass in the request body.
186
187 The test passes if the response has:
188
189 - Status code `200`.
190 - A `post` property in its data.
191 - Its `id` and `name` match the ones provided to the request.
192
193 ### Tear Down Created Record
194
195 To ensure consistency in the database for the rest of the tests after the above test is executed, utilize [Jest's setup and teardown hooks](https://jestjs.io/docs/setup-teardown) to delete the created record.
196
197 Use the `getContainer` function passed as a parameter to the `testSuite` function to resolve a service and use it for setup or teardown purposes
198
199 So, add an `afterAll` hook in the `describe` block for `POST /custom`:
200
201 ```ts title="integration-tests/http/custom-routes.spec.ts"
202 // other imports...
203 import BlogModuleService from "../../src/modules/blog/service"
204 import { BLOG_MODULE } from "../../src/modules/blog"
205
206 medusaIntegrationTestRunner({
207 testSuite: ({ api, getContainer }) => {
208 describe("Custom endpoints", () => {
209 // other tests...
210
211 describe("POST /custom", () => {
212 // ...
213 afterAll(() => async () => {
214 const blogModuleService: BlogModuleService = getContainer().resolve(
215 BLOG_MODULE
216 )
217
218 await blogModuleService.deletePosts(id)
219 })
220 })
221 })
222 },
223 })
224 ```
225
226 The `afterAll` hook resolves the `BlogModuleService` and use its `deletePosts` to delete the record created by the test.
227
228 ---
229
230 ## Test a DELETE API Route
231
232 Consider a `/custom/:id` API route created at `src/api/custom/[id]/route.ts`:
233
234 ```ts title="src/api/custom/[id]/route.ts"
235 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
236 import deletePostWorkflow from "../../../workflows/delete-post"
237
238 export async function DELETE(
239 req: MedusaRequest,
240 res: MedusaResponse
241 ) {
242 await deletePostWorkflow(req.scope).run({
243 input: {
244 id: req.params.id,
245 },
246 })
247
248 res.json({
249 success: true,
250 })
251 }
252 ```
253
254 This API route accepts an ID path parameter, and executes a `deletePostWorkflow` workflow that deletes a `Post` record by that ID. As with the previous example, the workflow's implementation isn't shown here.
255
256 To add tests for this API route, add the following to `integration-tests/http/custom-routes.spec.ts`:
257
258 export const deleteHighlights = [
259 ["21", "api.delete", "Send a DELETE request to the `/custom/:id` API route."]
260 ]
261
262 ```ts title="integration-tests/http/custom-routes.spec.ts" highlights={deleteHighlights}
263 medusaIntegrationTestRunner({
264 testSuite: ({ api, getContainer }) => {
265 describe("Custom endpoints", () => {
266 // ...
267
268 describe("DELETE /custom/:id", () => {
269 const id = "1"
270
271 beforeAll(() => async () => {
272 const blogModuleService: BlogModuleService = getContainer().resolve(
273 BLOG_MODULE
274 )
275
276 await blogModuleService.createPosts({
277 id,
278 name: "Test",
279 })
280 })
281
282 it("Deletes my custom", async () => {
283 const response = await api.delete(
284 `/custom/${id}`
285 )
286
287 expect(response.status).toEqual(200)
288 expect(response.data).toHaveProperty("success")
289 expect(response.data.success).toBeTruthy()
290 })
291 })
292 })
293 },
294 })
295 ```
296
297 This adds a new test for the `DELETE /custom/:id` API route. You use the `beforeAll` hook to create a `Post` record using the `BlogModuleService`.
298
299 In the test, you use the `api.delete` method to send a `DELETE` request to `/custom/:id`. The test passes if the response:
300
301 - Has a `200` status code.
302 - Has a `success` property in its data.
303 - The `success` property's value is true.
304
305 ---
306
307 ## Pass Headers in Test Requests
308
309 Some requests require passing headers. For example, all routes prefixed with `/store` must pass a publishable API key in the header.
310
311 The `get`, `post`, and `delete` methods accept an optional third parameter that you can pass a `headers` property to, whose value is an object of headers to pass in the request.
312
313 ### Pass Publishable API Key
314
315 For example, to pass a publishable API key in the header for a request to a `/store` route:
316
317 export const headersHighlights = [
318 ["10", "pak", "Create a publishable API key before the tests run."],
319 ["27", "headers", "Pass the publishable API key in the request's header."]
320 ]
321
322 ```ts title="integration-tests/http/custom-routes.spec.ts" highlights={headersHighlights}
323 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
324 import { ApiKeyDTO } from "@medusajs/framework/types"
325 import { createApiKeysWorkflow } from "@medusajs/medusa/core-flows"
326
327 medusaIntegrationTestRunner({
328 testSuite: ({ api, getContainer }) => {
329 describe("Custom endpoints", () => {
330 let pak: ApiKeyDTO
331 beforeAll(async () => {
332 pak = (await createApiKeysWorkflow(getContainer()).run({
333 input: {
334 api_keys: [
335 {
336 type: "publishable",
337 title: "Test Key",
338 created_by: "",
339 },
340 ],
341 },
342 })).result[0]
343 })
344 describe("GET /custom", () => {
345 it("returns correct message", async () => {
346 const response = await api.get(
347 `/store/custom`,
348 {
349 headers: {
350 "x-publishable-api-key": pak.token,
351 },
352 }
353 )
354
355 expect(response.status).toEqual(200)
356 expect(response.data).toHaveProperty("message")
357 expect(response.data.message).toEqual("Hello, World!")
358 })
359 })
360 })
361 },
362 })
363
364 jest.setTimeout(60 * 1000)
365 ```
366
367 In your test suit, you add a `beforeAll` hook to create a publishable API key before the tests run. To create the API key, you can use the `createApiKeysWorkflow` or the [API Key Module's service](!resources!/commerce-modules/api-key).
368
369 Then, in the test, you pass an object as the last parameter to `api.get` with a `headers` property. The `headers` property is an object with the key `x-publishable-api-key` and the value of the API key's token.
370
371 ### Send Authenticated Requests
372
373 If your custom route is accessible by authenticated users only, such as routes prefixed by `/admin` or `/store/customers/me`, you can create a test customer or user, generate a JWT token for them, and pass the token in the request's Authorization header.
374
375 First, install the `jsonwebtoken` package to generate JWT tokens:
376
377 ```bash npm2yarn
378 npm install jsonwebtoken
379 ```
380
381 Then, use it in your test to create a user or customer, generate a JWT token for them, and pass the token in the request's headers:
382
383 <Note title="Tips">
384
385 For custom actor types, you only need to change the `actorType` value in the `jwt.sign` method.
386
387 </Note>
388
389 <CodeTabs group="user-type">
390 <CodeTab label="Admin User" value="admin">
391
392 export const adminHighlights = [
393 ["9", "headers", "Define the headers that you'll pass in the request."],
394 ["11", "beforeEach", "Run before every test."],
395 ["21", "user", "Create the admin user."],
396 ["25", "authIdentity", "Create the auth identity for the user."],
397 ["40", "token", "Generate a JWT token for the user."],
398 ["52", "headers", "Set the token in the Authorization header."],
399 ["57", "headers", "Pass the headers to the request."]
400 ]
401
402 ```ts title="integration-tests/http/custom-routes.spec.ts" highlights={adminHighlights}
403 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
404 import jwt from "jsonwebtoken"
405 import { Modules } from "@medusajs/framework/utils"
406
407 medusaIntegrationTestRunner({
408 testSuite: ({ api, getContainer }) => {
409 describe("Custom endpoints", () => {
410 describe("GET /custom", () => {
411 const headers: Record<string, string> = {
412 }
413 beforeEach(async () => {
414 const container = getContainer()
415
416 const authModuleService = container.resolve(
417 Modules.AUTH
418 )
419 const userModuleService = container.resolve(
420 Modules.USER
421 )
422
423 const user = await userModuleService.createUsers({
424 email: "admin@medusa.js",
425
426 })
427 const authIdentity = await authModuleService.createAuthIdentities({
428 provider_identities: [
429 {
430 provider: "emailpass",
431 entity_id: "admin@medusa.js",
432 provider_metadata: {
433 password: "supersecret",
434 },
435 },
436 ],
437 app_metadata: {
438 user_id: user.id,
439 },
440 })
441
442 const token = jwt.sign(
443 {
444 actor_id: user.id,
445 actor_type: "user",
446 auth_identity_id: authIdentity.id,
447 },
448 "supersecret",
449 {
450 expiresIn: "1d",
451 }
452 )
453
454 headers["authorization"] = `Bearer ${token}`
455 })
456 it("returns correct message", async () => {
457 const response = await api.get(
458 `/admin/custom`,
459 { headers }
460 )
461
462 expect(response.status).toEqual(200)
463 })
464 })
465 })
466 },
467 })
468
469 jest.setTimeout(60 * 1000)
470 ```
471
472 </CodeTab>
473 <CodeTab label="Customer User" value="customer">
474
475 export const customerHighlights = [
476 ["11", "headers", "Define the headers that you'll pass in the request."],
477 ["13", "beforeEach", "Run before every test."],
478 ["23", "customer", "Create the customer."],
479 ["27", "authIdentity", "Create the auth identity for the customer."],
480 ["42", "token", "Generate a JWT token for the customer."],
481 ["54", "headers", "Set the token in the Authorization header."],
482 ["57", "pak", "Create a publishable API key"],
483 ["69", "headers", "Set the publishable API key in the request's header."],
484 ["74", "headers", "Pass the headers to the request."]
485 ]
486
487 ```ts title="integration-tests/http/custom-routes.spec.ts" highlights={customerHighlights}
488 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
489 import { ApiKeyDTO } from "@medusajs/framework/types"
490 import jwt from "jsonwebtoken"
491 import { createApiKeysWorkflow } from "@medusajs/medusa/core-flows"
492 import { Modules } from "@medusajs/framework/utils"
493
494 medusaIntegrationTestRunner({
495 testSuite: ({ api, getContainer }) => {
496 describe("Custom endpoints", () => {
497 describe("GET /custom", () => {
498 const headers: Record<string, string> = {
499 }
500 beforeEach(async () => {
501 const container = getContainer()
502
503 const authModuleService = container.resolve(
504 Modules.AUTH
505 )
506 const customerModuleService = container.resolve(
507 Modules.CUSTOMER
508 )
509
510 const customer = await customerModuleService.createCustomers({
511 email: "admin@medusa.js",
512
513 })
514 const authIdentity = await authModuleService.createAuthIdentities({
515 provider_identities: [
516 {
517 provider: "emailpass",
518 entity_id: "customer@medusa.js",
519 provider_metadata: {
520 password: "supersecret",
521 },
522 },
523 ],
524 app_metadata: {
525 user_id: customer.id,
526 },
527 })
528
529 const token = jwt.sign(
530 {
531 actor_id: customer.id,
532 actor_type: "customer",
533 auth_identity_id: authIdentity.id,
534 },
535 "supersecret",
536 {
537 expiresIn: "1d",
538 }
539 )
540
541 headers["authorization"] = `Bearer ${token}`
542
543
544 const pak = (await createApiKeysWorkflow(getContainer()).run({
545 input: {
546 api_keys: [
547 {
548 type: "publishable",
549 title: "Test Key",
550 created_by: "",
551 },
552 ],
553 },
554 })).result[0]
555
556 headers["x-publishable-api-key"] = pak.token
557 })
558 it("returns correct message", async () => {
559 const response = await api.get(
560 `/store/customers/me/custom`,
561 { headers }
562 )
563
564 expect(response.status).toEqual(200)
565 })
566 })
567 })
568 },
569 })
570
571 jest.setTimeout(60 * 1000)
572 ```
573
574 </CodeTab>
575 </CodeTabs>
576
577 In the test suite, you add a `beforeEach` hook that creates a user or customer, an auth identity, and generates a JWT token for them. The JWT token is then set in the `Authorization` header of the request.
578
579 You also create and pass a publishable API key in the header for the customer as it's required for requests to `/store` routes. Learn more in [this section](#pass-publishable-api-key).
580
581 ---
582
583 ## Upload Files in Test Requests
584
585 If your API route requires uploading a file, you can use the `form-data` library to create a `FormData` object, then pass the form data headers in the request.
586
587 First, run the following command to install the `form-data` package:
588
589 ```bash npm2yarn
590 npm install form-data
591 ```
592
593 Then, use it in your test to upload files:
594
595 ```ts title="integration-tests/http/custom-routes.spec.ts"
596 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
597 import FormData from "form-data"
598
599 medusaIntegrationTestRunner({
600 testSuite: ({ api, getContainer }) => {
601 describe("Custom endpoints", () => {
602 describe("GET /custom", () => {
603 it("upload file", async () => {
604 const form = new FormData()
605 form.append("files", Buffer.from("content 1"), "image1.jpg")
606 form.append("files", Buffer.from("content 2"), "image2.jpg")
607
608 const response = await api.post(`/custom`, form, {
609 headers: form.getHeaders(),
610 })
611
612 expect(response.status).toEqual(200)
613 expect(response.data).toHaveProperty("files")
614 expect(response.data.files).toEqual(
615 expect.arrayContaining([
616 expect.objectContaining({
617 id: expect.any(String),
618 url: expect.any(String),
619 }),
620 ])
621 )
622 })
623 })
624 })
625 },
626 })
627
628 jest.setTimeout(60 * 1000)
629 ```
630
631 You don't have to actually upload a file, you use the `form.append` method to append to a `files` field in the form data object, and you pass random content using the `Buffer.from` method.
632
633 Then, you pass to the `api.post` method the form data object as a second parameter, and an object with the `headers` property set to the form data object's headers as a third parameter.
634
635 If you're passing authentication or other headers, you can pass both the form data headers and the authentication headers in the same object:
636
637 ```ts title="integration-tests/http/custom-routes.spec.ts"
638 const response = await api.post(`/custom`, form, {
639 headers: {
640 ...form.getHeaders(),
641 ...authHeaders,
642 },
643 })
644 ```
645
646 ---
647
648 ## Write Tests for Feature-Flagged API Routes
649
650 If your API route is hidden behind a [feature flag], you can use the `env` option of `medusaIntegrationTestRunner` its feature flag.
651
652 For example:
653
654 ```ts title="integration-tests/http/custom-routes.spec.ts"
655 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
656
657 medusaIntegrationTestRunner({
658 env: {
659 FF_BLOG_FEATURE: true,
660 },
661 testSuite: ({ api, getContainer }) => {
662 // TODO write tests...
663 },
664 })
665 ```
666
667 The `env` option accepts an object of environment variables to set for the test suite.