This helper should be configured in codecept.conf.(js|ts)
Type: object
portnumber? Mock server porthoststring? Mock server hosthttpsOptsobject? key & cert values are the paths to .key and .crt files
MockServer powered by pactum
The MockServer Helper in CodeceptJS empowers you to mock any server or service via HTTP or HTTPS, making it an excellent tool for simulating REST endpoints and other HTTP-based APIs.
You can seamlessly integrate MockServer with other helpers like REST or Playwright. Here's a configuration example inside the codecept.conf.js file:
{
helpers: {
REST: {...},
MockServer: {
require: '@codeceptjs/pactum-mock-server',
// default mock server config
port: 9393,
host: '0.0.0.0',
httpsOpts: {
key: '',
cert: '',
},
},
}
}Interactions add behavior to the mock server. Use the I.addInteractionToMockServer() method to include interactions. It takes an interaction object as an argument, containing request and response details.
I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/hello'
},
response: {
status: 200,
body: {
'say': 'hello to mock server'
}
}
});When a real request is sent to the mock server, it matches the received request with the interactions. If a match is found, it returns the specified response; otherwise, a 404 status code is returned.
- Strong match on HTTP Method, Path, Query Params & JSON body.
- Loose match on Headers.
You can send different responses based on query parameters:
I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/users',
queryParams: {
id: 1
}
},
response: {
status: 200,
body: 'user 1'
}
});
I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/users',
queryParams: {
id: 2
}
},
response: {
status: 200,
body: 'user 2'
}
});- GET to
/api/users?id=1will return 'user 1'. - GET to
/api/users?id=2will return 'user 2'. - For all other requests, it returns a 404 status code.
When strict is set to false, it performs a loose match on query params and response body:
I.addInteractionToMockServer({
strict: false,
request: {
method: 'POST',
path: '/api/users',
body: {
name: 'john'
}
},
response: {
status: 200
}
});- POST to
/api/userswith the body containingnameas 'john' will return a 200 status code. - POST to
/api/userswithout thenameproperty in the body will return a 404 status code.
Happy testing with MockServer in CodeceptJS! 🚀
passedConfig
Start the mock server
portnumber? start the mock server with given port
Returns any void
Stop the mock server
Returns any void
An interaction adds behavior to the mock server
I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/hello'
},
response: {
status: 200,
body: {
'say': 'hello to mock server'
}
}
});// with query params
I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/hello',
queryParams: {
id: 2
}
},
response: {
status: 200,
body: {
'say': 'hello to mock server'
}
}
});interactionobject add behavior to the mock server
Returns any void