gpt4 book ai didi

reactjs - 用 Jest 测试时如何选择dom

转载 作者:行者123 更新时间:2023-11-28 21:35:56 42 4
gpt4 key购买 nike

it('render list',() => {
const handleClick = jest.fn()
const mockList = [{id:1011322,name:"Druig"},{id:1009284,name:"Dum Dum Dugan"},{id:101078,name:"Eddie Brock"}]
const div = document.createElement('div');
ReactDOM.render(<AutoComplete match={mockList} className={"autocomplete-items"} onClick={handleClick}/>, div);
debugger;
expect(document.querySelectorAll(".autocomplete-items li").length).toBe(3);
ReactDOM.unmountComponentAtNode(div);
})

无法选择呈现的 domdocument.querySelectorAll(".autocomplete-items li")当我调试 document.querySelectorAll(".autocomplete-items li") 它返回一个奇怪的对象。我在这里遗漏了什么吗?

最佳答案

您应该使用您的组件呈现的容器元素,div 元素而不是 document

index.jsx:

import React, { Component } from 'react';

class AutoComplete extends Component<any> {
render() {
return (
<div>
<ul className={this.props.className} onClick={this.props.onClick}>
{this.props.match.map(item => {
return <li key={item.id}>{item.name}</li>;
})}
</ul>
</div>
);
}
}

export default AutoComplete;

index.spec.jsx:

import React from 'react';
import ReactDOM from 'react-dom';
import AutoComplete from './index';

describe('AutoComplete', () => {
it('render list', () => {
const handleClick = jest.fn();
const mockList = [
{ id: 1011322, name: 'Druig' },
{ id: 1009284, name: 'Dum Dum Dugan' },
{ id: 101078, name: 'Eddie Brock' }
];
const div = document.createElement('div');
ReactDOM.render(<AutoComplete match={mockList} className={'autocomplete-items'} onClick={handleClick} />, div);
expect(div.querySelectorAll('.autocomplete-items li').length).toBe(3);
ReactDOM.unmountComponentAtNode(div);
});
});

单元测试结果:

 PASS  src/stackoverflow/58820204/index.spec.tsx (9.049s)
AutoComplete
✓ render list (32ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.788s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58820204

关于reactjs - 用 Jest 测试时如何选择dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58820204/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com