If your function is a pure function, you don’t need to mock anything, just provide input for the function, let the code execute different branch statements, and assert whether the return value is what you expect.
E.g.
index.ts:
export const inputValidation = (phnum, pincode, setvalue) => {
if (phnum?.length < 10 && setvalue) {
throw new Error('phnum must be 10 digit');
}
if (pincode?.length < 7 && setvalue) {
throw new Error('zipcode must be 7 digit');
}
return true;
};
index.test.ts:
import { inputValidation } from './';
describe('68413019', () => {
test('should throw error if the length of phnum lt 10 digit', () => {
expect(() => inputValidation('1', 123, true)).toThrowError('phnum must be 10 digit');
});
test('should throw error if the length of pincode lt 7 digit', () => {
expect(() => inputValidation('1234567890', '123', true)).toThrowError('zipcode must be 7 digit');
});
test('should return true if input is valid', () => {
expect(inputValidation('1234567890', '12345678', true)).toBeTruthy();
});
});
unit test result:
PASS examples/68413019/index.test.ts (9.085 s)
68413019
✓ should throw error if the length of phnum lt 10 digit (4 ms)
✓ should throw error if the length of pincode lt 7 digit
✓ should return true if input is valid (1 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 87.5 | 100 | 100 |
index.ts | 100 | 87.5 | 100 | 100 | 2-5
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 9.693 s, estimated 10 s
Ran all test suites related to changed files.