I am working on a simple method where i need to add test case using enzyme OR jest.
const export inputValidation = (phnum,pincode,setvalue) => {
//remove zipcode message
//remove phnum message
if (phnum?.length < 10 && setvalue) {
//phnum must be 10 digit(error message)
}
if (pincode?.length < 7 && setvalue) {
//zipcode must be 7 digit (error message)
}
//just return true or false
}
I never wrote function test case , I need some help on this.
test case i tried
describe(validation test case () =>{
it(CHECK IF PHONE NUMBER IS 10 DIGIT ELSE SET SOME MESSAGE ,()=>{
expect(inputValidation (12345678,1235667,true).ToEqual('')
})
})
else can we mock this function and check each parameter??
how do we check each input field is having limits??
i can check what the error message is displaying , i want to know how to frame it
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.