Testing with Jest
We are currently migration an internal tool from Javascript to Typescript. In that process, we also began adding unit tests with Jest (well, ts-jest to be precise).
Having mostly used unit testing tools in PHP or Java, I struggled a bit with creating mock objects. I found tons of blog posts that describe the process, but somehow none of them really worked.
In the end, I combined what I have read in different blog posts, and this is how I got things working. This is what I did. For better context: We are dealing with a CLI application that communicates with GitLab. To communicate with GitLab, we use the @gitbeaker/node package.
First, we import the needed mores, in our case we want to communicate with the GitLab Issues API:
import {Groups, Issues} from "@gitbeaker/core";
Next, and this is important, we need to tell jest that we want to mock dependencies from that package:
jest.mock('@gitbeaker/core');
In our tests, we can then create the mocks and pass them to our custom service. In this case, we create a mock object of the Issues Api and configure the create()
method to return something. Since in our logic we don't care about the return value of the create()
, I decided to return the own instance which technically is not correct but currently does not matter:
describe('Create project issues', () => {
test('Creating default issues for project', async () => {
const issuesApi = jest.mocked(new Issues());
issuesApi.create.mockReturnThis();
const service = new ProjectIssuesService(issuesApi);
// now you can call the method you want to set on the service object
});
});
You even can check expectations, e.g. how often the create()
method was called. In our implementation, we expect 2 calls of the create()
method:
describe('Create project issues', () => {
test('Creating default issues for project', async () => {
const issuesApi = jest.mocked(new Issues());
issuesApi.create.mockReturnThis();
const service = new ProjectIssuesService(issuesApi);
// now you can call the method you want to set on the service object
expect(issuesApi.create).toHaveBeenCalledTimes(2);
});
});
Now the test will fail if the create()
method is not called exactly 2 times.