1 import { Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Write Tests for Modules`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn about `moduleIntegrationTestRunner` from Medusa's Testing Framework and how to use it to write integration tests for a module's main service.
10
11 <Prerequisites
12 items={[
13 {
14 text: "Testing Tools Setup",
15 link: "/learn/debugging-and-testing/testing-tools"
16 }
17 ]}
18 />
19
20 ## moduleIntegrationTestRunner Utility
21
22 `moduleIntegrationTestRunner` creates integration tests for a module's service. The integration tests run on a test Medusa application with only the specified module enabled.
23
24 For example, consider a Blog Module with a `BlogModuleService` that has a `getMessage` method:
25
26 ```ts title="src/modules/blog/service.ts"
27 import { MedusaService } from "@medusajs/framework/utils"
28 import Post from "./models/post"
29
30 class BlogModuleService extends MedusaService({
31 Post,
32 }){
33 async getMessage(): Promise<string> {
34 return "Hello, World!"
35 }
36 }
37
38 export default BlogModuleService
39 ```
40
41 To create an integration test for the module's service, create the file `src/modules/blog/__tests__/service.spec.ts` with the following content:
42
43 ```ts title="src/modules/blog/__tests__/service.spec.ts"
44 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
45 import { BLOG_MODULE } from ".."
46 import BlogModuleService from "../service"
47 import Post from "../models/post"
48
49 moduleIntegrationTestRunner<BlogModuleService>({
50 moduleName: BLOG_MODULE,
51 moduleModels: [Post],
52 resolve: "./src/modules/blog",
53 testSuite: ({ service }) => {
54 describe("BlogModuleService", () => {
55 it("says hello world", () => {
56 const message = service.getMessage()
57
58 expect(message).toEqual("Hello, World!")
59 })
60 })
61 },
62 })
63
64 jest.setTimeout(60 * 1000)
65 ```
66
67 The `moduleIntegrationTestRunner` function accepts as a parameter an object with the following properties:
68
69 - `moduleName`: The registration name of the module.
70 - `moduleModels`: An array of models in the module. Refer to [this section](#write-tests-for-modules-without-data-models) if your module doesn't have data models.
71 - `resolve`: The path to the module's directory.
72 - `testSuite`: A function that defines [Jest](https://jestjs.io/) tests to run.
73
74 The `testSuite` function accepts as a parameter an object having the `service` property, which is an instance of the module's main service.
75
76 <Note title="Tip">
77
78 The type argument provided to the `moduleIntegrationTestRunner` function is used as the type of the `service` property.
79
80 </Note>
81
82 The tests in the `testSuite` function are written using [Jest](https://jestjs.io/).
83
84 ---
85
86 ## Run Tests
87
88 Run the following command to run your module integration tests:
89
90 ```bash npm2yarn
91 npm run test:integration:modules
92 ```
93
94 <Note title="Tip">
95
96 If you don't have a `test:integration:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](../page.mdx#add-test-commands).
97
98 </Note>
99
100 This runs your Medusa application and runs the tests available in any `__tests__` directory under the `src/modules` directory.
101
102 ---
103
104 ## Pass Module Options
105
106 If your module accepts options, you can set them using the `moduleOptions` property of the `moduleIntegrationTestRunner`'s parameter.
107
108 For example:
109
110 ```ts
111 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
112 import BlogModuleService from "../service"
113
114 moduleIntegrationTestRunner<BlogModuleService>({
115 moduleOptions: {
116 apiKey: "123",
117 },
118 // ...
119 })
120 ```
121
122 `moduleOptions` is an object of key-value pair options that your module's service receives in its constructor.
123
124 ---
125
126 ## Write Tests for Modules without Data Models
127
128 If your module doesn't have a data model, pass a dummy model in the `moduleModels` property.
129
130 For example:
131
132 ```ts
133 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
134 import BlogModuleService from "../service"
135 import { model } from "@medusajs/framework/utils"
136
137 const DummyModel = model.define("dummy_model", {
138 id: model.id().primaryKey(),
139 })
140
141 moduleIntegrationTestRunner<BlogModuleService>({
142 moduleModels: [DummyModel],
143 // ...
144 })
145
146 jest.setTimeout(60 * 1000)
147 ```
148
149 ---
150
151 ## Inject Dependencies in Module Tests
152
153 Some modules have injected dependencies, such as the [Event Module's service](!resources!/infrastructure-modules/event). When writing tests for those modules, you need to inject the dependencies that the module's service requires to avoid errors.
154
155 You can inject dependencies as mock dependencies that simulate the behavior of the original service. This way you avoid unexpected behavior or results, such as sending real events or making real API calls.
156
157 To inject dependencies, pass the `injectedDependencies` property to the `moduleIntegrationTestRunner` function.
158
159 For example:
160
161 export const mockDependenciesHighlights = [
162 ["11", "injectedDependencies", "Inject dependencies into the module's service."],
163 ["12", "Modules.EVENT_BUS", "The registration name of the dependency."],
164 ["12", "MockEventBusService", "The mock service to inject."]
165 ]
166
167 ```ts title="src/modules/blog/__tests__/service.spec.ts" highlights={mockDependenciesHighlights}
168 import { MockEventBusService, moduleIntegrationTestRunner } from "@medusajs/test-utils"
169 import { BLOG_MODULE } from ".."
170 import BlogModuleService from "../service"
171 import Post from "../models/post"
172 import { Modules } from "@medusajs/framework/utils"
173
174 moduleIntegrationTestRunner<BlogModuleService>({
175 moduleName: BLOG_MODULE,
176 moduleModels: [Post],
177 resolve: "./src/modules/blog",
178 injectedDependencies: {
179 [Modules.EVENT_BUS]: new MockEventBusService(),
180 },
181 testSuite: ({ service }) => {
182 describe("BlogModuleService", () => {
183 it("says hello world", async () => {
184 const message = await service.getMessage()
185
186 expect(message).toEqual("Hello, World!")
187 })
188 })
189 },
190 })
191
192 jest.setTimeout(60 * 1000)
193 ```
194
195 `injectedDependencies`'s value is an object whose keys are registration names of the dependencies you want to inject, and the values are the mock services.
196
197 In this example, you inject a mock Event Module service into the `BlogModuleService`. Medusa exposes a `MockEventBusService` class that you can use to mock the Event Module's service.
198
199 For other modules, you can create a mock service that implements the same interface as the original service. Make sure to use the same registration name as the original service when injecting it.
200
201 ---
202
203 ### Other Options and Inputs
204
205 Refer to [the Test Tooling Reference](!resources!/test-tools-reference/moduleIntegrationTestRunner) for other available parameter options and inputs of the `testSuite` function.
206
207 ---
208
209 ## Database Used in Tests
210
211 <Prerequisites
212 items={[
213 {
214 text: "A PostgreSQL server is running."
215 },
216 {
217 text: "The PostgreSQL user that the tests connect with can create databases."
218 },
219 {
220 text: "The moduleModels property has at least one data model."
221 }
222 ]}
223 />
224
225 The `moduleIntegrationTestRunner` function creates a database named `medusa-{module-name}-integration-{worker-id}`, where `{module-name}` is the value of the `moduleName` property, and `{worker-id}` is the ID of the Jest worker running the test file. You can set a different name with the `dbName` property.
226
227 The database is created from the module's data models before each test, and its tables are dropped after each test. Unlike `medusaIntegrationTestRunner`, the database itself isn't dropped when the tests end, so the next test run reuses it.
228
229 The tests connect to the PostgreSQL server using the `DB_HOST`, `DB_PORT`, `DB_USERNAME`, and `DB_PASSWORD` environment variables, which default to `localhost`, `5432`, `postgres`, and an empty password respectively.
230
231 <Note type="warning">
232
233 The test runner only creates the database if the module has data models. If `moduleModels` is empty and the runner can't find data models in the module's directory, the database isn't created, and your tests either fail with an error like `database "medusa-blog-integration-1" does not exist` or time out while connecting to the database.
234
235 If your module doesn't have data models, pass a dummy model as explained in the [Write Tests for Modules without Data Models](#write-tests-for-modules-without-data-models) section.
236
237 </Note>
238
239 To manage that database, such as changing its name or perform operations on it in your tests, refer to [the Test Tooling Reference](!resources!/test-tools-reference/moduleIntegrationTestRunner).