我是反应测试库的新手,很长一段时间以来我一直在尝试测试一个功能。例如,我想检查当单击按钮时是否调用给定函数并且它抛出错误。因此,我们将非常感谢任何帮助,如果可能的话,请与我分享任何有用的资源。
登录.js
export default class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
};
}
handleClose = (event, reason) => { };
validate = () => { };
change = (e) => { };
onSubmit = (e) => { };
render() {
return (<div>...</div>);
}
}
Run Code Online (Sandbox Code Playgroud)
完整: https: //github.com/blaise82/react-testing-library-try/blob/master/src/views/SignIn.js
这是我的测试
it('should submit form', async () => {
const { getByLabelText, getByText, container, debug } = render(<SignIn />);
const change = jest.fn();
const onSubmit = jest.fn();
const email = …Run Code Online (Sandbox Code Playgroud) 我正在用来react-testing-library测试一个简单的组件,其中有一个嵌套的react-router-dom <Link>,我收到此错误:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用react testing library测试我的antd应用程序,但我不断收到此错误:
类型错误:无法读取未定义的属性“addListener”
我使用自定义渲染,但错误似乎来自“渲染”方法。
const customRender = (ui, options) => render(ui, { wrapper: TestingWrapper, ...options }) ^
我什至使用相同版本的 react 和 react-dom(这似乎是 rtl 的常见问题)。
“反应”:“17.0.1”,“反应dom”:“17.0.1”,
有问题的组件似乎是这样的:
import React, {
lazy,
Suspense
} from 'react';
import List from 'antd/lib/list';
const Stories = (props) => {
return(
<div className="stories-container">
<div>
<h1 className="StoriesTitle">Stories</h1>
</div>
<div className="StoryListContainer">
<Suspense fallback={<Spin />}>
<List
itemLayout="vertical"
size="default"
pagination={pagination}
dataSource={stories}
renderItem={item =>
<StoryItem
item={item}
deleteFn={onDelete}
loggedIn={loggedIn}
stories={stories}
/>
}
/>
</Suspense>
</div>
</div>
);
} …Run Code Online (Sandbox Code Playgroud) getByText和 和有什么区别getByTestId?
当我测试 React 组件时,这两个功能之间存在一些差距。
在代码中测试失败getByText,但在getByTestId.
我有代码,当单击某个元素时,标题的颜色变为红色。
为什么会有这样的差别呢?
Container我省略了和的样式组件Content。这具有“切换”道具以将颜色更改为红色。
这是getByText代码:
const { getByText } = render(<ListPresenter content={ListText} />);
const colorChangedText = getByText(/the party/);
fireEvent.click(colorChangedText);
screen.debug(); // The result of render I want !
expect(colorChangedText).toHaveStyle("color: red"); * failed
Run Code Online (Sandbox Code Playgroud)
这是getByTestId代码:
const { getByText } = render(<ListPresenter content={ListText} />);
fireEvent.click(getAllByTestId("list-element-toggle")[0]);
screen.debug(); // The result of render I want !
const colorChangedText = getAllByTestId("list-element-content")[0];
expect(colorChangedText).toHaveStyle("color: red"); * success
Run Code Online (Sandbox Code Playgroud)
这是渲染的组件:
const …Run Code Online (Sandbox Code Playgroud) 我正在将类组件重构为功能组件。
在我的测试文件中,我使用的是酶,但我正在迁移到反应测试库
这是我正在使用酶进行的测试
it('should change module when clicked button login', () => {
const wrapper = mount(<SignUp setModuleCallback={jest.fn()} />)
const instance = wrapper.instance()
jest.spyOn(instance, 'setModule')
wrapper.find('button#login-button').simulate('click')
expect(instance.setModule).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)
这就是我尝试使用react-testing-library 做的事情
it('should change module when clicked button login', async () => {
const { getByTestId } = render(<SignUp setModuleCallback={jest.fn()} />)
const instance = getByTestId('submit')
jest.spyOn(instance, 'setModule')
const button = await waitFor(() => getByTestId('submit'))
act(() => {
fireEvent.click(button)
})
expect(instance.setModule).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误
我使用搜索栏组件构建了一个简单的反应应用程序。搜索栏组件包含一个输入。为了进行测试,我使用 Jest 和 React 测试库。我想编写一个测试,测试当在输入的值中输入某些内容时,输入的占位符是否消失。
Searchbar.test.tsx
test("SearchBar placeholder gets replaced by search string", () => {
const handleSearchRequest = jest.fn();
render(<SearchBar searchInputValue="Hello World"/>);
const searchInput = screen.getByPlaceholderText("Search");
expect(searchInput).toBeFalsy(); //test fails
// expect(searchInput).not.toBeInTheDocument(); //test fails
// expect(searchInput).toBeNull(); //test fails
});
Run Code Online (Sandbox Code Playgroud)
搜索栏.tsx
<Input
placeholder="Search"
value={currentValue}
/>
Run Code Online (Sandbox Code Playgroud)
我应该如何编写这个测试有什么想法吗?
我需要一些帮助。我是阿波罗客户端反应变量的新手。有一个组件,消息的显示取决于本地状态(apollo 缓存)中的值的变量。在测试将不同值传递到该变量的组件期间,模拟 apollo 缓存将如何?
消息.tsx
const Message: FC = ({ children }) => {
const message = useReactiveVar(messageVar);
return (
<>
{!!message && (
<Alert>
<Typography className={classes.title}>
Due to scheduled data updates...
</Typography>
</Alert>
)}
{children}
</>
);
};
Run Code Online (Sandbox Code Playgroud)
缓存.ts
export const cache: InMemoryCache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
maintenanceMessage: {
read() {
return messageVar();
},
},
},
},
},
});
const maintenanceMessageVar = makeVar<null>(null)
Run Code Online (Sandbox Code Playgroud)
消息.test.tsx
it('render message', () => {
const { getByText } = …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试 useQuery 挂钩。测试 (expect(screen.getByText(/Loading.../)).not.toBeInTheDocument()) 似乎失败。我只是不断在 dom 中加载文本,而不是标题。尽管mockResolved已被分配/知道为什么会发生这种情况吗?整个目标是测试 isLoading 和 isError。下面是代码
索引.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();
ReactDOM.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
document.getElementById("root")
);
Run Code Online (Sandbox Code Playgroud)
应用程序
import React, { useState, Fragment } from "react";
import { useQuery } from "react-query";
import { getManagers } from "./api/index";
import CustomInputSelect from "./components/CustomInputSelect";
import { processEmployeeData } from "./utils/index";
import "./App.scss";
const App …Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的组件,我试图模拟 API 调用来获取一些稍有延迟的电影。
我想编写一个测试来测试电影是否被收集然后渲染到屏幕上。
我试图用来screen.getAllByTestId做到这一点,但它总是失败。就好像它没有重新渲染,因此没有获得更新的更改。
我在元素上添加了一个 testid,并且可以在 DOM 中看到它们。
任何人都可以帮忙解释为什么他们出现后找不到他们吗?
这是完整的组件代码...
import './App.css';
import { useEffect, useState } from 'react';
function App() {
const [movies, setMovies] = useState([]);
useEffect(() => {
// simulate API call to get
setTimeout(() => {
const movies = [{ title: 'Titanic' }, { title: 'Back To The Future' }];
setMovies(movies);
}, 1000);
}, []);
return (
<div>
{movies.length > 0 && (
<div>
{movies.map((x) => (
<div data-testid='movies'>{x.title}</div>
))}
</div>
)}
</div>
); …Run Code Online (Sandbox Code Playgroud) 我有一个 React 组件,里面有 Ant Design Modal,我正在尝试测试当单击按钮时模态是否打开:
组件:
const ModalComponent = () => {
const [visible, setVisible] = useState(false);
return (
<>
<Button type="primary" onClick={() => setVisible(true)}>
Open Modal
</Button>
<Modal
title="Modal title"
centered
visible={visible}
onOk={() => setVisible(false)}
onCancel={() => setVisible(false)}
>
<p>some contents...</p>
<p>some contents...</p>
<p>some contents...</p>
</Modal>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
测试文件:
test('modal opening', async () => {
const { queryByText } = render(<ModalComponent />);
fireEvent.click(queryByText('Open Modal'));
await waitFor(() => expect(queryByText('Modal title')).toBeInTheDocument());
});
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试调试时,模态 DOM 永远不会在测试中呈现,因此测试失败。发生这种情况的原因可能是模态内容是在 body 标记内的组件 DOM 树外部创建的?
reactjs ×8
jestjs ×4
antd ×2
testing ×2
enzyme ×1
javascript ×1
node.js ×1
react-query ×1
ts-jest ×1