docs: fixes and improvements to testing docs (#11244)

* docs: fixes and improvements to testing docs

* generate files
This commit is contained in:
Shahed Nasser
2025-01-31 15:36:20 +02:00
committed by GitHub
parent 105e73b523
commit d6480c4d0a
12 changed files with 224 additions and 38 deletions

View File

@@ -304,3 +304,66 @@ In the test, you use the `api.delete` method to send a `DELETE` request to `/cus
- Has a `success` property in its data.
- The `success` property's value is true.
---
## Pass Headers in Test Requests
Some requests require passing headers. For example, all routes prefixed with `/store` must pass a publishable API key in the header.
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.
For example, to pass a publishable API key in the header for a request to a `/store` route:
export const headersHighlights = [
["10", "pak", "Create a publishable API key before the tests run."],
["27", "headers", "Pass the publishable API key in the request's header."]
]
```ts title="integration-tests/http/custom-routes.spec.ts" highlights={headersHighlights}
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import { ApiKeyDTO } from "@medusajs/framework/types"
import { createApiKeysWorkflow } from "@medusajs/medusa/core-flows"
medusaIntegrationTestRunner({
testSuite: ({ api, getContainer }) => {
describe("Custom endpoints", () => {
let pak: ApiKeyDTO
beforeAll(async () => {
pak = (await createApiKeysWorkflow(getContainer()).run({
input: {
api_keys: [
{
type: "publishable",
title: "Test Key",
created_by: ""
}
]
}
})).result[0]
})
describe("GET /custom", () => {
it("returns correct message", async () => {
const response = await api.get(
`/store/custom`,
{
headers: {
"x-publishable-api-key": pak.token
}
}
)
expect(response.status).toEqual(200)
expect(response.data).toHaveProperty("message")
expect(response.data.message).toEqual("Hello, World!")
})
})
})
},
})
jest.setTimeout(60 * 1000)
```
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).
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.

View File

@@ -93,3 +93,52 @@ If you don't have a `test:integration` script in `package.json`, refer to the [M
</Note>
This runs your Medusa application and runs the tests available under the `integrations/http` directory.
---
## Test That a Workflow Throws an Error
You might want to test that a workflow throws an error in certain cases. To test this:
- Disable the `throwOnError` option when executing the workflow.
- Use the returned `errors` property to check what errors were thrown.
For example, if you have a step that throws this error:
```ts title="src/workflows/hello-world.ts"
import { MedusaError } from "@medusajs/framework/utils"
import { createStep } from "@medusajs/framework/workflows-sdk"
const step1 = createStep("step-1", () => {
throw new MedusaError(MedusaError.Types.NOT_FOUND, "Item doesn't exist")
})
```
You can write the following test to ensure that the workflow throws that error:
```ts title="integration-tests/http/workflow.spec.ts"
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import { helloWorldWorkflow } from "../../src/workflows/hello-world"
medusaIntegrationTestRunner({
testSuite: ({ getContainer }) => {
describe("Test hello-world workflow", () => {
it("returns message", async () => {
const { errors } = await helloWorldWorkflow(getContainer())
.run({
throwOnError: false
})
expect(errors.length).toBeGreaterThan(0)
expect(errors[0].error.message).toBe("Item doesn't exist")
})
})
},
})
jest.setTimeout(60 * 1000)
```
The `errors` property contains an array of errors thrown during the execution of the workflow. Each error item has an `error` object, being the error thrown.
If you threw a `MedusaError`, then you can check the error message in `errors[0].error.message`.

View File

@@ -58,6 +58,8 @@ moduleIntegrationTestRunner<HelloModuleService>({
})
},
})
jest.setTimeout(60 * 1000)
```
You use the `moduleIntegrationTestRunner` function to add tests for the `hello` module. You have one test that passes if the `getMessage` method returns the `"Hello, World!"` string.
@@ -69,12 +71,12 @@ You use the `moduleIntegrationTestRunner` function to add tests for the `hello`
Run the following command to run your module integration tests:
```bash npm2yarn
npm run test:modules
npm run test:integration:modules
```
<Note title="Tip">
If you don't have a `test:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](../../page.mdx#add-test-commands).
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).
</Note>

View File

@@ -37,6 +37,8 @@ moduleIntegrationTestRunner<HelloModuleService>({
// TODO write tests
},
})
jest.setTimeout(60 * 1000)
```
The `moduleIntegrationTestRunner` function accepts as a parameter an object with the following properties:
@@ -63,12 +65,12 @@ The tests in the `testSuite` function are written using [Jest](https://jestjs.io
Run the following command to run your module integration tests:
```bash npm2yarn
npm run test:modules
npm run test:integration:modules
```
<Note title="Tip">
If you don't have a `test:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](../page.mdx#add-test-commands).
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).
</Note>
@@ -115,6 +117,8 @@ moduleIntegrationTestRunner<HelloModuleService>({
moduleModels: [DummyModel],
// ...
})
jest.setTimeout(60 * 1000)
```
---

View File

@@ -22,14 +22,6 @@ npm install --save-dev @medusajs/test-utils@latest
Writing tests with `@medusajs/test-utils`'s tools requires installing and configuring Jest in your project.
{/* TODO remove this note at some point in the future */}
<Note>
If your Medusa project was created after September 3rd, Jest is already installed and configured.
</Note>
Run the following command to install the required Jest dependencies:
```bash npm2yarn
@@ -56,6 +48,7 @@ module.exports = {
testEnvironment: "node",
moduleFileExtensions: ["js", "ts", "json"],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["./integration-tests/setup.js"],
}
if (process.env.TEST_TYPE === "integration:http") {
@@ -67,6 +60,14 @@ if (process.env.TEST_TYPE === "integration:http") {
}
```
Next, create the `integration-tests/setup.js` file with the following content:
```js title="integration-tests/setup.js"
const { MetadataStorage } = require("@mikro-orm/core")
MetadataStorage.clear()
```
---
## Add Test Commands