fifietcie
fifietcie

Reputation: 17

Function clear is not a spy or a call to a spy

I'm trying to test the navigation bar expecially the log out button but I keep getting this error

[Function clear] is not a spy or a call to a spy!

here is my test

import React from "react";
import { render, fireEvent } from "@testing-library/react";
import NavBar from "../components/NavBar";
import { vi, test, describe, expect } from "vitest";

describe("NavBar component", () => {
  test("render the navBar correctly", () => {
    const setTokenMock = vi.fn();
    render(<NavBar setToken={setTokenMock} />);
  });

  test("Log out if log out button is clicked", () => {
    const setTokenMock = vi.fn();

    const { getByText } = render(<NavBar setToken={setTokenMock} />);

    fireEvent.click(getByText("Déconnexion"));

    expect(setTokenMock).toHaveBeenCalledWith("");

    expect(localStorage.clear).toHaveBeenCalled();
  });
});

Can you tell me what am I doing wrong ?

Thank you for you help

Upvotes: 0

Views: 2843

Answers (1)

Adam Jenkins
Adam Jenkins

Reputation: 55613

You aren't spying on localStorage.clear, so vi can't determine if it's been called or not.

const localStorageClearSpy = vi.spyOn(localStorage,'clear')

...

expect(localStorageClearSpy).toHaveBeenCalled();

Upvotes: 1

Related Questions