如何在React组件中测试div的样式



我有一个切换按钮,可以显示和隐藏组件中的div。对测试来说相当陌生,不知道如何测试切换。本质上,当studentDisplay为false时,我有一个将div的显示设置为none的样式。当studentDisplay为true时,样式设置为显示块。任何建议和/或想法都将不胜感激。

我想测试的组件中的方法

import React, {useState} from 'react';
export default function App() {
const [studentDisplay, setStudentDisplay] = useState(false);
function handleStudentDisplay() {
setStudentDisplay(!studentDisplay);
}
return (
<div className="App">
<button onClick={handleStudentDisplay}>
<span>Student Name</span>
</button>
<div style={studentDisplay ? {display:'block'} : {display:'none'}}>
Student 
</div>
</div>
);
}

测试示例

import React from 'react';
import renderer from 'react-test-renderer';
import { render, fireEvent, act } from '@testing-library/react';
describe('Student Toggle', () => {
it('should display student', () => {
const eventHandler = jest.fn();
const { getByRole } = render(<button onClick={eventHandler}/>);
act(() => {
const button = getByRole('button');
fireEvent.click(button);
});
expect(eventHandler).toHaveBeenCalled();
//how do I test? <div style={studentDisplay ? {display:'block'} : {display:'none'}}>
});
});

您可以从RTL使用expect。下面是一个测试元素显示属性的例子,您可以使用id或元素添加className或fetch,

const TargetElement = document.getElementsByClassName('button-class-name');
const style = window.getComputedStyle(TargetElement[0]);
expect(style.display).toBe('none');
expect(style.display).toBe('block');

关于测试react元素样式的更多信息,甚至可能使用样式组件,下面是Ilya Zykin的一篇内容丰富的文章。

最新更新