【发布时间】: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