Integration with Test Runner
In your project, you are likely using a test runner like Jest
or Mocha
. After writing tests as described in the quick-start guide, when you run your test framework, it will automatically detect and execute the itdoc
test code (describeAPI()
, itdoc()
, etc.).
During this process, itdoc
extracts the API requests and responses from the test code you wrote to generate documentation.
✅ Important Things
When running tests, the test runner must execute against the path that includes the itdoc
test code. If that path is not included, the test runner will not detect the itdoc
test code.
Therefore, the test
script in package.json
should specify the path that includes the itdoc
test code.
- Jest
- Mocha
{
"scripts": {
"test": "jest ."
}
}
{
"scripts": {
"test": "mocha ."
}
}
For detailed configuration methods, please refer to the official documentation of each test runner.
Test Setup and Teardown
If you want to perform pre/post-processing tasks for tests, you can use the hooks provided by each test runner as they are.
For example, in Jest
, you can use hooks like beforeAll
and afterAll
to perform tasks before and after tests.
describeAPI(
HttpMethod.POST,
"/signup",
{
summary: "User Registration API",
tag: "Auth",
description: "Registers a new user with username and password.",
},
app,
(apiDoc) => {
beforeEach(() => { // Jest Provided Hook
console.log("before each")
})
itDoc("Successful registration", () => {
return apiDoc
.test()
.req()
.body({
username: field("Username", "testuser"),
password: field("Password", "Password123!"),
})
.res()
.status(HttpStatus.CREATED)
.body({
message: field("Success message", "User created successfully"),
})
})
})
afterAll(() => { // Jest Provided Hook
console.log("afterAll")
})
Example of Using Mocking
itdoc
can be used alongside various mocking libraries supported by Jest
and Mocha
. However, to ensure reliable API documentation, itdoc
recommends using minimal mocking wherever possible.
Below is an example of mocking time information in an API response:
import * as MockDate from "mockdate"
describeAPI(
HttpMethod.POST,
"/api/v1/users/login",
{
summary: "User Login API",
tag: "Auth",
description: "User login API",
},
app,
(apiDoc) => {
let mockedDate = new Date("2023-10-01T00:00:00Z")
beforeEach(() => {
MockDate.set(mockedDate) // Apply mocking
})
afterEach(() => {
MockDate.reset() // Reset mocking
});
itDoc("Successfully logs in with a valid username and password.", () => {
return apiDoc
.test()
.prettyPrint()
.req()
.body({
username: field("username", "penek"),
password: field("password", "penek"),
})
.res()
.status(HttpStatus.OK)
.body({
"detail" : {
"token" : field("Generated JWT token", (val) => {
assertJWT(val, "penek");
}),
"expire" : field("Token expiration time", mockedDate.toISOString()) // Validate using the mocked time
}
})
})
})