React-3 组件测试

117 阅读1分钟
  1. 组件测试 VS. 单元测试
  • 测试目标
    • 组件测试:测试DOM元素是否被渲染(不含样式)
    • 单元测试:测试用户事件,与页面元素的交互
  • 例子
    • 组件测试: 测试Hello组件 Arrange: 安排好多有先要条件和输入

设置输入参数name为“World”
Act: render被测试的组件
调用render函数,render()
Assert: 验证测试组件的行为和预期结果的一致
验证DOM中是否存在“Hello World”

  • 组件测试: 测试Hello组件 Arrange: 安排好多有先要条件和输入

设置输入密码password的值为“12345”
Act: render被测试的组件
调用验证密码函数verifyPassword(password)
Assert: 验证测试组件的行为和预期结果的一致
验证输出结果是否为false

  1. 代码实例
test('renders "Hello World"', ()=>{
  // Arrange: prepare input data is 'World'
  const name = 'World';
  // Act: render a React component to the DOM
  render(<Hello name ={name}>);
  // Assertions: using query to make assertions
  expect(screen.getByText(/Hello, World/i)).toBeInTheDocument();
});

getByText比getByRole的优先级要低,所以有先用getByRole,他们都用来选择第一个匹配元素, “/Hello, World/i”中的/.../放正则表达式,“i”表示忽略大小写。

import Todo from '../app/todo';
import React from 'react';
import { mount } from 'enzyme';
 
test('TodoComponent renders the text inside it', () => {
  const todo = { id: 1, done: false, name: 'Buy Milk' };
  const wrapper = mount(
    <Todo todo={todo} />
  );
  const p = wrapper.find('.toggle-todo');
  expect(p.text()).toBe('Buy Milk');
});

代码来源