【问题标题】:Jest : TypeError : Cannod read property 'fn' of undefined开玩笑:TypeError:无法读取未定义的属性“fn”
【发布时间】:2021-06-23 10:50:42
【问题描述】:

我有一个必须使用 jest 测试的标头组件。 header 组件接受三个 props setIsDark(function)、setMode(function)、isDark(boolean)。我想写一个简单的测试,但它给了我这个错误:Cannot read property 'fn' of undefined

这是我的测试文件tests/header.js

import React from "react";
import { render } from "@testing-library/react";
import Header from "../header";
import jest from "jest-mock";

test("temp", () => {
  expect(true).toBe(true);
});

test("header renders some text", () => {
  const setIsDark = jest.fn();
  const setMode = jest.fn();
  const isDark = true;

  const { debug } = render(
    <Header setMode={setMode} isDark={isDark} setIsDark={setIsDark} />,
  );
  debug();
});

编辑:不使用开玩笑的模拟我得到TypeError: instace.getTotalLength is not a function

有人可以指出我在这里做错了什么。提前致谢。

【问题讨论】:

  • 你能分享你的Header组件

标签: javascript reactjs testing jestjs


【解决方案1】:

那么您正在导入 jest-mock 库而不是 jest

如果您在项目中正确安装了 jest,则不必在测试中导入它,因此如果您删除 import jest from "jest-mock"; 你可以使用jest.fn() 没有任何错误。

【讨论】:

  • 没有开玩笑,我得到这个错误TypeError: instance.getTotalLength is not a function
  • 可以尝试导入import '@testing-library/jest-dom';
  • 我试过了,还是一样的错误。我在我的标题中使用 svg ..它是否与此相关。
  • 是的,我猜是的。您的测试应该可以正常工作
  • 我猜 jsdom 不支持 svg..所以有什么解决方法
猜你喜欢
  • 2018-06-17
  • 2020-11-19
  • 2023-03-03
  • 2020-07-10
  • 2017-12-15
  • 2020-06-26
  • 2017-10-18
  • 2022-01-18
  • 2019-08-08
相关资源
最近更新 更多