功能清除不是间谍或调用间谍

问题描述 投票:0回答:1

我正在尝试测试导航栏,特别是注销按钮,但我不断收到此错误

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

这是我的测试

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();
  });
});

你能告诉我我做错了什么吗?

谢谢你的帮助

reactjs typescript testing vitest spy
1个回答
0
投票

您没有监视

localStorage.clear
,因此
vi
无法确定它是否被调用。

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

...

expect(localStorageClearSpy).toHaveBeenCalled();

© www.soinside.com 2019 - 2024. All rights reserved.