【问题标题】:Jest - test if function is called if prop is present开玩笑 - 如果存在 prop,则测试是否调用函数
【发布时间】:2020-12-17 11:31:23
【问题描述】:

我想写一个测试,看看如果传入了正确的prop,我的组件内部的useEffect函数是否被调用。

PropDetail.js

import React, { useState, useEffect } from "react";

function PropDetail({ propID }) {
  
  const [propStatus, setPropStatus] = useState(null);

  useEffect(() => {
    if (!propID) return;

    setPropStatus(propID)

  }, [propID]);

  return <p>{propStatus}</p>
}

export default PropDetail;

PropDetail.test.js

import React from "react";
import { shallow } from "enzyme";

import PropDetail from '../PropDetail'

const props = {  }
describe('PropDetail', () => {
  const wrapper = shallow(<PropDetail {...props} />)

  describe('With no propID', () => {
    it('returns null if no propID passed in', () => {
      expect(wrapper.html()).toBe(null)
    })
  })
  describe('With propID passed in', () => {
    beforeEach(() => {
      wrapper.setProps({ propID: 'PROPID' })
    })
    it('Runs useEffect with propID', () => {
      expect(wrapper.setPropStatus().toHaveBeenCalledTimes(1);
    })
  })
})

我在控制台中遇到的错误是“匹配器错误:接收到的值必须是模拟或间谍函数”和“接收到的值:未定义”。

我对编写测试很陌生,所以我不确定这是否是正确的起点,或者我正在测试错误的东西!

【问题讨论】:

  • FWIW,useEffect 仅在 mount 时运行,而不是浅层。
  • 嗨,我看到你还在。请您参加question from last year?

标签: javascript reactjs jestjs enzyme


【解决方案1】:

您不想测试 React 的某个功能,例如 useEffect。您需要以“调用 useEffect 时发生的情况”之类的方式测试您的代码。

您可以在初始渲染时测试propStatus 的值。然后更新propID,然后测试propStatus的值。是您期望或渴望的价值吗?

这样您就可以测试您编写的实际代码的正确性。当您看到 propStatus 发生变化时,您也会知道 useEffect 是在没有直接测试该函数的情况下被调用的。

您还可以使用yarn test --coverage 测试覆盖率。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-16
    • 2018-12-15
    • 1970-01-01
    • 2020-08-24
    • 2018-02-25
    • 2021-02-02
    • 2020-03-10
    • 2019-04-06
    相关资源
    最近更新 更多