Home > OS >  Best practice testing return value from a function with Jest React Testing Library
Best practice testing return value from a function with Jest React Testing Library

Time:10-27

I have a very simple salary calculator function that receives as parameters input values ​​inside a form and that in the end returns the result with its calculations.

Logic Function

export function calcAnnualSalary(
  monthlySalary: string,
  healthPlan?: string,
  transpostationTicket?: string,
  mealTicket?: string,
  valueSaturday?: boolean
) {
  const annualSalary =
    parseFloat(monthlySalary.replace(/\./g, '').replace(',', '.')) * 12
  const thirteenth = parseFloat(
    monthlySalary.replace(/\./g, '').replace(',', '.')
  )
  const extraHoliday =
    parseFloat(monthlySalary.replace(/\./g, '').replace(',', '.')) / 3
  const totalAnnualCrude = annualSalary   thirteenth   extraHoliday

  return {
    annualSalary,
    thirteenth,
    extraHoliday,
    totalAnnualCrude,
  }
}


Testing

With that, I created a very simple test with hardcoded values, I would like to know if this is the best practice to test function calculation logic. To avoid hardcoded for example, I should get the value inside the form, what would it suggest?

import {CalcAnnualSalary} from '~src/components/app/Calculators/CalcAnnualSalary'
import * as Calc from '~src/utils/calculators/'
import * as Lib from '~src/utils/testing-library'

describe('CalculatorAnnualSalary', () => {
  it('expect return gross annual salary', () => {
    const {annualSalary} = Calc.calcAnnualSalary('1.000,00')
    expect(annualSalary).toEqual(12000)
  })
})

CodePudding user response:

In the test, you should provide the test double and test data as simply as possible. That reduces the complexity and facilitates testing.

Whether you use static data or dynamically generated test data, keep it simple. With simple test data, you can also more easily predict the desired results.

The test is predictable, when writing test cases, you should provide the desired result before running the test cases, if your input is complicated, the desired result is difficult to calculate, you need to execute the code in your brain with this data.

Use simple test data to test every code branch, the logical fragment of a function.

  • Related