After writing the basic code for my GitHub action for the actionhackathon. I was thinking of how to increase the quality of code and to follow the software engineering best practices.
I thought I should write tests for my action as it is an essential part of software engineering life-cycle.
Writing tests in JS
Since most of the code in my GitHub action is using axios to send API requests to the DEV server. I have to test the API requests.
To test this code, I have come across Axios Mock adapter, which mocks the API calls for testing purposes.
I have used this mocking-library with Jest, a testing framework for JavaScript.
Installing libraries
npm install axios-mock-adapter --save-dev
npm install jest --save-dev
Mocking request
Below is the example from the official docs.
var axios = require("axios");
var MockAdapter = require("axios-mock-adapter");
var mock = new MockAdapter(axios);
mock.onGet("/users").reply(200, {
users: [{ id: 1, name: "John Smith" }],
});
axios.get("/users").then(function (response) {
console.log(response.data);
});
Testing with Jest
// require libraries
var mock = new MockAdapter(axios);
// Mocking
mock.onPost(url + "/articles").reply(201, {});
// Writing Test
test("Testing a 201 (created) response", () => {
var data = {};
expect(createPost(data, "secret")).toBeTruthy(); // Test passes if the value is truthy
});
Now add a script in your package.json
as
...
"scripts": {
....
"test": "jest" // To run jest
},
...
Now run the following command
npm run test
You'll see All test passed messages in the console.
Top comments (0)