开玩笑-测试是否在prop存在的情况下调用了函数

时间:2020-08-28 14:03:07

标签: javascript reactjs jestjs enzyme

我想编写一个测试,看看是否传入了正确的道具,是否调用了组件内部的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);
    })
  })
})

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

我对编写测试非常陌生,所以我不确定这是正确的起点还是测试错误的东西!

1 个答案:

答案 0 :(得分:0)

您不想测试React的功能,例如useEffect。您将希望以某种方式测试代码,例如“调用useEffect时会发生什么”。

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

通过这种方式,您可以测试编写的实际代码的正确性。当您看到propStatus中的更改时,您还将知道在没有直接测试该功能的情况下调用了useEffect

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