You would do something like this:
describe('rateTermCalc', () => {
let component: YourComponentClass; // replace with the actual name of your class
beforeEach(() => {
component = new YourComponentClass();
// If you can spy on termYearsDiff, do so here. Otherwise, you might need to refactor your code.
jest.spyOn(component, 'termYearsDiff').mockImplementation((x, min, max) => x >= min && x <= max);
});
it.each([
[181, '6 months'],
[183, '1 year'],
[365, '1 year'],
[366, '2 years'],
[730, '2 years'],
[731, '3 years'],
[1095, '3 years'],
[1096, '4 years'],
[1460, '4 years'],
[1461, '5 years'],
[1825, '5 years'],
[1826, '7 years'],
[2555, '7 years'],
[2556, '10 years'],
])('should set termText correctly for remainingDays %i', (remainingDays, expectedTermText) => {
component.remainingDays = remainingDays;
component.rateTermCalc();
expect(component.termText).toBe(expectedTermText);
});
});
Breakdown of what I did:
Step 1. Mock the termYearsDiff
function: Since termYearsDiff
is a method of the same class, I don't think you can easily spy on it (could be wrong on this..my angular spy knowledge is rusty at best), but let's assume you can. If not, you might need to refactor your code to make it something a bit more testable.
Step 2. Set up the test table: For it.each
, you'll set up a table where each row represents a test case. Each row will contain:
- The value of
this.remainingDays
.
- The expected value of
this.termText
.
Step 3. Write the test: For each test case, you'll set the value of this.remainingDays
, call rateTermCalc
, and then check if this.termText
matches the expected value.
NOTE: I did this primarily pseudocode with what you provided...didn't run this locally or in an editor since it would just error on my without your full termYearDiff
code, I couldn't fully gleam the termYearDiff
algo, but have general idea of what its doing, and i was too lazy to write my scaffolding code for this...but if you provide more detail we could get a working example going.