Reputation: 1615
There is a ValidationError
(custom made) being thrown on my invert
function if no string
is provided:
const invert = (str) => {
if (str === '') throw new ValidationError('String must no be empty.');
return str;
};
This line of code is not getting full coverage by my assertion while using Jest:
expect(() => invert('')).toThrow(ValidationError);
Is there a way to get coverage for this line?
Upvotes: 1
Views: 478
Reputation: 102257
You should have two test cases at least. One test throws an error, and one test is normal. E.g.
index.ts
:
export class ValidationError extends Error {
constructor(message) {
super(message);
}
}
export const invert = (str) => {
if (str === '') throw new ValidationError('String must no be empty.');
return str;
};
index.test.ts
:
import { invert, ValidationError } from './';
describe('64271662', () => {
it('should throw validation error if string is empty', () => {
expect(() => invert('')).toThrow(ValidationError);
});
it('should return string', () => {
expect(invert('teresa teng')).toBe('teresa teng');
});
});
unit test result with 100% coverage:
PASS src/stackoverflow/64271662/index.test.ts (9.867s)
64271662
✓ should throw validation error if string is empty (4ms)
✓ should return string (1ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.042s
Upvotes: 1