Executing Code in Tests
For certain use cases, the built-in test steps may not be enough flexibility to test your APIs thoroughly. In these cases, you can add custom code actions that will execute when your tests are called.
To add custom code to your test, add the Code Run step.
Your code should export a function through module.exports
. Here is an example:
module.exports = (context) => {
if (1 + 1 === 2 ) {
return {results: "Math rocks!"};
}
else {
throw new Error("Because math!");
}
}
The function takes one argument โ context
, which is an object holding all the variables in the test flow (data returned from previous API calls, test variables, environment variables, etc).
The function should return an object. Any data in the object will be added to the test context and can be used by subsequent actions. See the following test flow as an example:
Intentionally Failing Tests
In addition to adding and modifying data, you may want to use code snippets to perform complex validations on data (like regex-matching strings or summing up numbers). If you want to cause a test to fail, just throw an exception in your code like so:
module.exports = (context) => {
throw "This action will fail the test"
}
Whatever message you send in the exception will be added to the test results:
Allowed Libraries
The ability to run code at any point within your test definition already gives you a lot of flexibility to manipulate data, get the current date, etc. However, there are instances where built in JS functions is just not enough. This is why we allow certain limited libraries.
Below is an example of how you would use an allowed library, in this case the crypto library to calculate HMAC signature. You will add the library by using require
.
module.exports = (context) => {
const crypto = require('crypto');
const date = (new Date()).toISOString().split('.')[0] + "+00:00";
const sampleSigData = "sample_test" + ':' + date;
const sig = crypto.createHmac('sha256', "client_secret").update(sampleSigData).digest("base64");
return {result: sig}
}
Current allowed libraries are listed below.
Updated almost 2 years ago