我正在为带有情感样式的组件编写单元测试。
import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
const Selected = styled.div`
width: 40%;
height: auto;
background: ${props => props.color};
`;
const SelectedColor = ({ color }) => {
return <Selected color={color} />;
};
Run Code Online (Sandbox Code Playgroud)
我已经编写了这个测试,但它从未通过。
it('Should change the background color', () => {
const color = 'rgb(140, 52, 30)';
const { container } = render(<SelectedColor color={color} />);
expect(container).toHaveStyle(`background: ${color}`);
});
Run Code Online (Sandbox Code Playgroud) 我正在使用 cypress 和反应测试库来对我的组件执行单元测试。但是,当测试执行时我遇到以下错误
\n\n“超出赛普拉斯命令超时‘4000ms’。”
\n\n我注意到我编写的实际测试成功了。但是以某种方式插入的“毕竟”挂钩存在错误。我的测试规范中没有“毕竟”挂钩。我想知道可以从哪里调用它,因为我的代码中没有它。
\n\n附加信息:我正在使用在plugins/index.js 文件中添加的 webpack 和 istanbul 插件
\n\n测试规范.js
\n\nimport React from \'react\';\nimport {render, fireEvent, cleanup} from \'@testing-library/react\';\nimport Greeting from \'../../src/utils/testUtils/components/Greeting\';\n\ndescribe(\'react-testing-library\', () => { \n\n it(\'renders View Details component\', () => { \n const component = render(<Greeting />);\n component.getByText(\'Hello\');\n })\n})\nRun Code Online (Sandbox Code Playgroud)\n\n我的组件 -greeting.js
\n\nimport React from \'react\';\n\nexport default function Greeting() {\n return (\n <div>{\'Hello\'}</div>\n );\n}\nRun Code Online (Sandbox Code Playgroud)\n\n赛普拉斯\\support\\index.js
\n\nimport \'./commands\';\nimport \'@cypress/code-coverage/support\';\nRun Code Online (Sandbox Code Playgroud)\n\ncypress\\plugins\\index.js
\n\n\nconst webpack = require(\'@cypress/webpack-preprocessor\')\nconst webpackOptions = {\n …Run Code Online (Sandbox Code Playgroud) javascript unit-testing reactjs cypress react-testing-library
我创建了一个公开钩子的上下文以方便使用。在这个钩子中,我已经确保在渲染页面之前预加载一些数据,如下所示:
export const MyContext = React.createContext({} as any);
function useMyContext() {
const context = React.useContext(MyContext);
if (context === undefined) {
throw new Error('useMyContext must be used within a MyContext');
}
return context;
}
function MyContextProvider(props: any) {
const client = useApolloClient();
const { user } = React.useContext(UserContext);
const [data, setData ] = React.useState({});
const findSomethingFromUser = () => {
return client.query({
query: FIND_SOMETHING_FROM_USER,
variables: { userId: user.id },
});
};
const load = () => {
findSomethingFromUser()
.then(({ data, errors …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-testing-library react-hooks react-hooks-testing-library
这是我使用 MockedProvider 的方式。如何在模拟数组中模拟重新获取?
const mocks = [{
request: {
query: GET_USERS_BY_FACILITY,
variables: {
facility: 300
}
},
result: {
data: {
GetUsersByFacility: [{
nuId: 'Q916983',
userName: faker.internet.userName(),
profileKey: 'testKey',
profileValue: 'testValue',
__typename: 'FacilityUser'
}]
}
},
refetch: () => {
return {
data: {
GetUsersByFacility: [{
nuId: 'Q916983',
userName: faker.internet.userName(),
profileKey: 'testKey',
profileValue: 'testValue',
__typename: 'FacilityUser'
}]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
该测试用例在触发删除事件时调用 refetch 函数。
it('should be able to click on delete user', async () => {
const {getByTestId} = render( …Run Code Online (Sandbox Code Playgroud) 在测试库中,我试图找到一种方法来查找其子级与条件匹配的元素:让我们在测试中呈现的容器中考虑这一点:
<div class="classA">
<div class="classB">
<div class="classC">
some text
</div>
</div>
<div class="classB">
<div class="classC">
more text
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我想找到
<div class="classB">
<div class="classC">
some text
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我尝试过:
getByText(container, 'some text', {selector: 'classB'})但它返回了
<div class="classC">
some text
</div>
Run Code Online (Sandbox Code Playgroud)
我缺少什么来找到包含此文本的容器/组件/父级?
我有这个功能组件。
搜索.js
function Search() {
const [term, setTerm] = useState('sun');
function handleOnChange(e) {
if (!e.target.value) {
return false;
}
setTerm(e.target.value);
return true;
}
return <input type="text" onChange={handleOnChange} placeholder="Search" />
}
Run Code Online (Sandbox Code Playgroud)
搜索.test.js
import { render, fireEvent } from '@testing-library/react';
import Search from '.';
describe('when type a valid term', () => {
it('update the state', () => {
const { getByPlaceholderText } = render(<Search />;
// this doesn't work. The handleOnChange method is private. How to deal with this?
const handlerSpy = …Run Code Online (Sandbox Code Playgroud) 我对测试还很陌生,所以尽量温和!我正在尝试设置react-testing-library,但遇到了令人困惑的错误消息:
我定义了一个自定义渲染器,其中包含我的所有提供程序,包括。还原Provider:
import React from 'react';
import { render } from '@testing-library/react'
import { ThemeProvider } from 'styled-components';
import { defaultTheme } from 'shared/theme';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from 'reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
const AllTheProviders = ({ children }) => {
return (
<Provider store={store}>
<ThemeProvider theme={defaultTheme}>
{children}
</ThemeProvider>
</Provider>
)
}
const customRender = (ui, options?) =>
render(ui, { wrapper: …Run Code Online (Sandbox Code Playgroud) 我有一个小型应用程序redux-dynamic-modules,用作存储,react-router用于路由,所有组件都是带有useState、useHistory、useLocation、useSelector等钩子的函数组件useDispatch。
我想设置react-testing-library来测试组件,正如文档中所述,我需要设置一个自定义render().
所以这是我的index.tsx
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import { store } from "./redux/store";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
Run Code Online (Sandbox Code Playgroud)
这是我的 App.tsx
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { SearchPage } from "./pages/search/search-page";
import …Run Code Online (Sandbox Code Playgroud) typescript reactjs redux react-testing-library redux-dynamic-modules
沿着这篇 MDN 文章的思路,我有一个由三个不同元素的组合标记的复选框输入:一个标签、一个文本字段,然后是另一个标签。
因此,复选框输入有一个aria-labelledby属性,其值类似于label1 text-field label2。
<input type="checkbox" aria-labelledby="allow-up-to num words-in-between" />
<div>
<label id="allow-up-to">allow up to</label>
<input id="num" type="text" value="0" />
<label id="words-in-between">words in between</label>
</div>
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我尝试根据该标签获取复选框。
getByLabelText('text of label1')我可以使用或成功获取输入getByLabelText('text of label2'),但为其提供完整的串联标签getByLabelText('text of label1 value of text-field text of label2')会导致找不到任何内容。
getByLabelText("allow up to"); // works
getByLabelText("words in between") // works
getByLabelText("allow up to 0 words in between") // does not work
Run Code Online (Sandbox Code Playgroud)
尝试getByLabelText('value of text-field')也不起作用,但即使我从 中删除文本字段aria-labelledby,我仍然无法使用 …
我是反应测试库的新手,所以这可能很容易,但我目前有一个从流畅的 UI 导入的下拉列表,当我尝试测试它时,当前收到“该元素没有值设置器”错误使用 React 测试库。这是我的渲染函数。
import { Dropdown, IDropdownStyles, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { Stack } from 'office-ui-fabric-react/lib/Stack';
render()
{
return (
<div className="LandingPage">
<h3>Here are some options</h3>
<form onSubmit={this.handleSubmit}>
<Stack>
<Stack.Item align="center">
<Dropdown
placeholder="Select an option"
label="Select an option"
options={this.options}
styles={this.dropdownStyles}
onChange={this.handleChange}
data-testid="myId"
/>
</Stack.Item>
</Stack>
</form>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是失败的行:
const dropdownOption: IDropdownOption = {
key: "0",
text: "dropdownOption"
}
fireEvent.click(queryByTestId("myId"), { target: { value: 'B' }, option: dropdownOption })
Run Code Online (Sandbox Code Playgroud)
The given element does not have …Run Code Online (Sandbox Code Playgroud) reactjs ×8
jestjs ×4
javascript ×3
testing ×2
typescript ×2
unit-testing ×2
cypress ×1
fluent-ui ×1
graphql ×1
react-hooks ×1
react-hooks-testing-library ×1
redux ×1