首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

期望toContain文本来自jest、酶和React中的一组值

在Jest、Enzyme和React测试中,你可以使用toContain匹配器来检查文本是否包含在一组值中。以下是这些库的具体用法:

Jest

Jest的toContain匹配器用于数组或字符串,检查它们是否包含指定的值。

代码语言:javascript
复制
test('array contains value', () => {
  const array = [1, 2, 3];
  expect(array).toContain(2);
});

test('string contains substring', () => {
  const str = 'Hello, world!';
  expect(str).toContain('world');
});

Enzyme

Enzyme是一个用于测试React组件的库。你可以使用find方法结合text方法来检查组件的文本内容。

代码语言:javascript
复制
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

test('component contains text', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.text()).toContain('Expected Text');
});

如果你想检查组件内的某个特定元素是否包含文本,你可以使用find方法来定位该元素。

代码语言:javascript
复制
test('specific element contains text', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.find('.specific-class').text()).toContain('Expected Text');
});

React Testing Library

React Testing Library鼓励编写更接近用户行为的测试。你可以使用screen.getByTextqueryByText来查找包含特定文本的元素。

代码语言:javascript
复制
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('component contains text', () => {
  render(<MyComponent />);
  expect(screen.getByText(/Expected Text/i)).toBeInTheDocument();
});

在这个例子中,/Expected Text/i是一个正则表达式,i标志表示不区分大小写。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券