Next.js | Jest + React testing library + Typescript 单元测试框架搭建及实现
    		       		warning:
    		            这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
    		        
        		                
                
// 引入Next.js的测试工具和React Testing Library
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
 
// 引入需要测试的组件
import ExampleComponent from '../components/ExampleComponent';
 
// 使用describe定义测试套件
describe('ExampleComponent 组件的测试', () => {
  // 使用test定义测试案例
  test('点击按钮后,页面上的文本会更新', () => {
    // 使用render方法渲染组件
    render(<ExampleComponent />);
    
    // 使用screen.getByRole获取按钮元素
    const button = screen.getByRole('button', { name: /点击我/i });
    // 使用screen.getByText获取文本元素
    const text = screen.getByText(/初始文本/i);
    
    // 使用userEvent.click模拟用户点击事件
    userEvent.click(button);
    
    // 使用toBeInTheDocument断言元素是否在文档中
    expect(text).toBeInTheDocument();
    // 断言文本是否更新
    expect(text).toHaveTextContent(/更新后的文本/i);
  });
});这段代码展示了如何使用Next.js、Jest和React Testing Library来编写一个简单的组件测试案例。它定义了一个测试套件,并在其中创建了一个测试案例,用于验证点击按钮后,页面上的文本是否如预期那样更新。
评论已关闭