简体   繁体   中英

Jest unit test fails but it shouldnt

I have this method that returns Boolean. It works as it should but in unit tests it fails. The method looks like this:

 const isRushHour = (date: string): boolean => {
  let isRushHour: boolean = false;
  let isFriday: boolean = new Date(date).getDay() === 5;
  let selectedTime: string = new Date(date).toLocaleTimeString(
    navigator.language,
    {
      hour: "2-digit",
      minute: "2-digit",
    }
  );

  let isRushHourRange: boolean =
    selectedTime >= "15:00" &&
    selectedTime <= "19:00" ;

  if (isFriday && isRushHourRange) {
    isRushHour = true;
  }

  return isRushHour;
};

it Basically checks if date is friday and if it its between the time range. However everything is fine when checking with console f.ex;

console.log(isRushHour("2022-01-07T19:00"))

This will return true and it should be like this !

But in jest i tried with .toBe(true), .toBeTruthy(), and to toEqual(true)

    expect(calculator.isRushHour("2022-01-07T19:00")).toBe(true);

Exactly the same string.

But the test fails with message:

   expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

This fixed the issue:

   beforeEach(() => {
  jest.spyOn(window.navigator, "language", "get");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM