Reputation: 1282
I want to get a better understanding of how to test these kinds of functions in Typescript using mocha. Namely, I have the following small file:
import { Request, Response } from 'express';
export const ping = (req: Request, res: Response) => {
res.send('pong');
};
export const health = (req: Request, res: Response) => {
res.send('OK');
};
This exercise may be trivial since there's not much to test here but below I have some basic mocha tests:
describe('Health Tests', () => {
it('Check ping', () => {
expect(ping).to.not.be.null;
})
it('Check health', () => {
expect(health).to.not.be.null;
})
})
When I run code coverage on this test I get: 50% Stmts | 100% Branch | 0% Funcs | 50% Lines. Especially because this is such a small bit of code, I want to get 100% coverage on all of the categories if possible. Would anyone have any advice on how to accomplish this? Also, could someone please explain why I have 0% coverage for functions? By checking ping
or health
, am I not also then calling a function and hence, testing that as well.
Any advice would be much appreciated!
Upvotes: 1
Views: 1613
Reputation: 102337
You need to use some mock/stub library like sinonjs. Here is unit test solution with 100% coverage:
index.ts
:
import { Request, Response } from 'express';
export const ping = (req: Request, res: Response) => {
res.send('pong');
};
export const health = (req: Request, res: Response) => {
res.send('OK');
};
index.test.ts
:
import { ping, health } from './';
import sinon from 'sinon';
describe('63065938', () => {
describe('#ping', () => {
it('should pass', () => {
const mReq = {};
const mRes = { send: sinon.stub() };
ping(mReq, mRes as any);
sinon.assert.calledWith(mRes.send, 'pong');
});
});
describe('#health', () => {
it('should pass', () => {
const mReq = {};
const mRes = { send: sinon.stub() };
health(mReq, mRes as any);
sinon.assert.calledWith(mRes.send, 'OK');
});
});
});
unit test result with 100% coverage:
63065938
#ping
✓ should pass
#health
✓ should pass
2 passing (12ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Upvotes: 2