我在 React 组件中使用了 Material-UI 组件。因此,我需要<MuiThemeProvider></MuiThemeProvider>在我的测试中围绕所有组件应用该组件。
我的组件位于单独的文件夹中:
./src/components/Header/Header.tsx
./src/components/Header/Header.test.ts
./src/components/Header/...
./src/components/Footer/Footer.tsx
./src/components/Footer/Footer.test.ts
./src/components/Footer/...
// etc.
Run Code Online (Sandbox Code Playgroud)
测试必须如下所示:
import React from 'react';
import { render } from '@testing-library/react';
import Header from './Header';
it('matches snapshot', () => {
const container = render(
// This theme provider is necessary since my components depend on it.
// But rather don't want to include this in all my components.
<MuiThemeProvider theme={theme}>
<Header />
</MuiThemeProvider>
);
expect(container).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)
但是现在我必须在我的每个测试中定义 MuiThemeProvider。
是否可以对我的所有测试执行一次?
我正在尝试测试反应渲染。据我所知,有几种方法可以查找我定义的元素。
我什么时候应该定义类名的“角色”或“测试ID”实例,角色和测试ID之间有什么区别?
我有一个 react 组件,它从另一个第三方库(例如:Ant 或 bootstrap )导入一个组件,现在我想测试这个组件的 onClick 行为。
但是getByTestId或者getByText比较困难,因为第三方库没有thiese属性或者有时候html标签里没有文字。如何获取第三方 dom 并使用 react-testing-library 对其进行测试?
PS:有人可能会说,我们不必测试 bootstrap 组件,因为这是他们的事,但这会降低我们的测试覆盖率。(例如:如果我们将许多回调函数 props 作为事件处理程序传递给 a bootstrap 组件,我们必须测试回调增加测试覆盖率)
我在我的项目中使用 react-testing-library & jest。
我的问题是:当我测试我的父组件时,我可以将我的子组件与测试隔离吗?
这是我的组件:
export const Parent: FC = ({items}) => {
return (
<>
<ListComponent items={items} />
<ChildWillBeIsolated />
</>
)
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
import React from "react";
import { Parent as Component } from "./";
import { render } from "@testing-library/react";
const items = [
{
title: "A"
id: 1
},
{
title: "B"
id: 2
}
]
it("renders without crashing", async () => {
const wrapper = render(
<Component items={items} />
);
expect(wrapper).toMatchSnapshot();
wrapper.unmount();
});
Run Code Online (Sandbox Code Playgroud)
所以在这里我 …
我在测试用例文件中模拟了一个函数。
MyService.getConfigsForEntity = jest.fn().mockReturnValue(
new Promise(resolve => {
let response = [];
resolve(response);
})
);
Run Code Online (Sandbox Code Playgroud)
现在我希望该文件中的所有测试用例都使用这个模拟
describe('Should render Component Page', () => {
it('should call the API', async () => {
const {container} = render(<MyComp entityName='entity1'/>);
await wait(() => expect(MyService.getConfigsForEntity).toHaveBeenCalled());
});
});
Run Code Online (Sandbox Code Playgroud)
唯一的问题是只有一个测试用例我想以不同的方式模拟返回值。
但之前和之后的所有其他测试用例都可以使用全局模拟。
describe('Should call API on link click', () => {
it('should call the API on link click', async () => {
const spy = jest.spyOn(MyService, 'getConfigsForEntity ').mockReturnValue(
new Promise(resolve => {
let response = [{
"itemName": "Dummy" …Run Code Online (Sandbox Code Playgroud) 我如何才能测试 onkeypress 功能的功能?
当前的 onkeypress 函数已插入到元素中。
试图测试如何测试onkeypress函数被调用的输入框?
如何测试它的调用方式?
玩笑、反应测试库和反应
任何帮助将不胜感激!
成分 -
import React, { useState } from 'react';
function Search({ setWeather }) {
const [city, setCity] = useState('');
async function getWeather(e) {
if (e.key === 'Enter') {
e.preventDefault();
e.target.blur();
console.log('in here');
try {
const key = process.env.REACT_APP_API_KEY;
const uri = `APIURIHERE`;
const response = await fetch(uri);
const responseJson = await response.json();
setWeather(responseJson);
setCity('');
} catch (error) {
console.log('api error', error);
}
}
}
return (
<div>
<label htmlFor='search-box'>
<input …Run Code Online (Sandbox Code Playgroud) 我有以下非常简单的组件:
const { openDrawer, setOpenDrawer } = useContext(DrawerContext)
const toggleDrawer = (open: boolean) => {
setOpenDrawer(open)
}
return (
<Button data-testid="ClickIndicator" onClick={() => toggleDrawer(true)} />
)
Run Code Online (Sandbox Code Playgroud)
我试图通过简单地检查是否正在调用该方法来测试它。该按钮是一个样式组件,它返回一个 div 现在我正在尝试使用以下测试来测试此组件:
it('should open drawer when ClickIndicator is clicked', () => {
const mockOnClick = jest.fn()
const { getByTestId } = render(<Button />)
const clickIndicator = getByTestId('ClickIndicator')
fireEvent.click(clickIndicator)
expect(mockOnClick).toHaveBeenCalledTimes(1)
})
Run Code Online (Sandbox Code Playgroud)
但它只是不会将它作为被调用返回。收到的呼叫数保持为 0,我不知道为什么。有没有人可以帮助我?任何帮助,将不胜感激!
我正在学习 Jest 和 React,并尝试使用 Material-UI。我编写这个简单的测试只是为了检查事情如何工作:
import React from 'react';
import { render, fireEvent, configure} from '@testing-library/react';
import { TextField } from '@material-ui/core';
configure({ testIdAddribute: 'id' });
describe('Testing events', () => {
test('onChange', () => {
const onChangeMock = jest.fn();
const { getByTestId } = render(
<TextField id="test" onChange={onChangeMock} type="text" />
);
fireEvent.change(getByTestId('test', { target: { value: 'foo' } }));
expect(onChangeMock.mock.calls.length).toBe(1);
});
});
Run Code Online (Sandbox Code Playgroud)
但这个测试失败了:
expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
Run Code Online (Sandbox Code Playgroud)
我在这里不明白什么?
我有一个有事件的反应类组件
constructor(props) {
super(props);
this.monthRef = React.createRef();
this.yearRef = React.createRef();
this.state = {
moIndexActive: props.initialMonth - 1,
yeIndexActive: years.findIndex(y => y === `${props.initialYear}`),
};
}
//some code blablabla
// this error occur in this line bellow
componentWillUnmount() {
this.monthRef.current.removeEventListener('scroll');
this.yearRef.current.removeEventListener('scroll');
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 React 测试库来测试这个,我已经在谷歌上搜索过,但还没有找到解决方案,请帮助我。如果有任何方法可以模拟React测试库或Jest上的removeEventListener。提前致谢。
我需要覆盖 React 测试库中的默认 testID 属性。使用 Jest 作为测试框架。
为此,我在单个测试文件级别遵循了此处给出的步骤。
有什么方法可以在全局(项目)级别进行此配置,以便项目中的所有测试文件都将遵循此类自定义配置,并且不需要在测试文件级别显式定义自定义配置?
reactjs ×9
jestjs ×7
javascript ×1
material-ui ×1
onkeypress ×1
spy ×1
testing ×1
unit-testing ×1