DEV Community

Ishaan Sheikh
Ishaan Sheikh

Posted on • Edited on

Writing tests for my GitHub action

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.

SDLC

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
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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
});

Enter fullscreen mode Exit fullscreen mode

Now add a script in your package.json as

...
"scripts": {
    ....
    "test": "jest" // To run jest
  },
...
Enter fullscreen mode Exit fullscreen mode

Now run the following command

npm run test
Enter fullscreen mode Exit fullscreen mode

You'll see All test passed messages in the console.

References

Source Code

GitHub logo frikishaan / dev-action

GitHub action to create a post on DEV.to for each release published on Github.

Top comments (0)