【发布时间】:2021-01-16 20:11:18
【问题描述】:
我是 Jest 的新手,我正在尝试为状态值编写测试用例,我想更新测试套件中的状态值,任何人都可以提供帮助。谢谢。
例如:我的组件 从'react'导入反应,{useState};
import Child from './Child';
function Parent(props) {
const [isFetching, setState] = useState(false);
return (
<div className="parent">
<h1>Parent</h1>
{isFetching ? 0 : 1}
<Child called={setState} />
{ isFetching ? <div>
<p>from state true</p>
<button onClick={clickmefn}>click me</button>
</div>: null
}
</div>
);
}
export default (Parent);
我的测试套件因未找到该元素而失败 wrapper.find('p').text() 无法找到它,因为状态为 false。
import Parent from './Parent';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import { mount, shallow } from 'enzyme';
const setHookState = (newState) => jest.fn().mockImplementation((state) => [
newState,
(newState) => {}
])
const reactMock = require('react')
describe('ComponentWithHook component', () => {
let wrapper
beforeEach(() => {
wrapper = shallow(<Parent/>)
});
it('should render itself', () => {
const changeCounter = jest.fn();
const handleClick = jest.spyOn(React, "useState");
handleClick.mockImplementation(isFetching => [isFetching, changeCounter]);
expect(wrapper.find('p').text()).toBe('from state true');
})
})
【问题讨论】:
-
我建议避免模拟状态。相反,只需在组件上进行交互,使其进入该状态。我知道你在使用酶,但是看看 React 测试库的原则,我认为它们是有道理的:testing-library.com/docs/guiding-principles
-
组件上的交互?如果可能的话,我可以举个例子吗?
-
如中,模拟按钮点击等,然后测试显示“这样那样的文本”。
-
是的,我们可以这样做,但是我不想在视图中显示按钮和测试,是否可以只在测试文件中添加它自己?
-
测试组件的内部结构非常容易出错。您应该考虑编写集成测试,而不是意味着您渲染您的组件,与之交互并将 DOM 与预期的内容进行比较。另请参阅react testing library 的作者blog of kentcdodds,recommended 作为用于测试反应组件的工具。特别是this
标签: reactjs unit-testing jestjs enzyme