我正在尝试测试我的路由器是否按预期工作。但我无法让路由器指向另一个位置/
这是我的简化测试代码。
App.tsx
import React from 'react';
import {Route, Switch, BrowserRouter} from 'react-router-dom';
const App: React.FC = () => {
return (
<div>
<BrowserRouter>
<Switch>
<Route path={'/test'}>test</Route>
<Route path={'/'}>index</Route>
</Switch>
</BrowserRouter>
</div>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
App.test.tsx
import React from 'react';
import App from './App';
import {MemoryRouter} from 'react-router-dom';
import {render} from '@testing-library/react';
test('renders /test route', async () => {
const app = render(
<MemoryRouter initialEntries={['/test']} initialIndex={0}>
<App/>
</MemoryRouter>);
expect(app.getByText(/test/i)).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息
Error: Unable to find an element …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试反应组件并使用expect(elm).not.toBeVisible()但没有成功。
更新 3
我已将代码缩减为这种更简单的形式:
// ./TestItem.js
import React from 'react'
import './TestItem.css'
export default ({ hide }) => {
return <div className={hide ? 'shouldHide' : ''}>Text</div>
}
// ./__tests__/TestItem.test.js
import React from 'react'
import { render } from 'react-testing-library'
import TestItem from '../TestItem'
import 'jest-dom/extend-expect'
import 'react-testing-library/cleanup-after-each'
test.only('TestItem should render correctly', async () => {
const { getByText, debug } = render(<TestItem hide={true} />)
const itemNode = getByText('Text')
debug()
expect(itemNode).not.toBeVisible()
})
// ./TestItem.css
.shouldHide {
display: none;
} …Run Code Online (Sandbox Code Playgroud) reactjs jestjs create-react-app semantic-ui-react react-testing-library
我正在尝试测试以下情况:
为此,我有2个提供者:
两者都有自定义的挂钩,公开了这些组件的共享逻辑,即:fetchResource / expireSesssion
当获取的资源返回401状态时,它将通过共享setState方法在身份验证提供程序中设置isExpiredSession值。
AuthenticationContext.js
从'react'导入React,{createContext,useState};
const AuthenticationContext = createContext([{}, () => {}]);
const initialState = {
userInfo: null,
errorMessage: null,
isExpiredSession: false,
};
const AuthenticationProvider = ({ authStateTest, children }) => {
const [authState, setAuthState] = useState(initialState);
return (
<AuthenticationContext.Provider value={[authStateTest || authState, setAuthState]}>
{ children }
</AuthenticationContext.Provider>);
};
export { AuthenticationContext, AuthenticationProvider, initialState };
Run Code Online (Sandbox Code Playgroud)
useAuthentication.js
import { AuthenticationContext, initialState } from './AuthenticationContext';
const useAuthentication = () => {
const [authState, …Run Code Online (Sandbox Code Playgroud) reactjs react-testing-library react-hooks react-hooks-testing-library
我有类似的代码(仅保留相关代码)
function App() {
const [values, setValues] = useState([]);
async function onUpload(event) {
if (event?.target.files?.length) {
const data = await event.target.files[0].text();
const json = JSON.parse(data);
setValues(json);
} else {
throw new Error('couldnt get files');
}
}
return (
<div>
{Boolean(!values.length) && (
<input data-testid="upInput" accept="application/JSON" type="file" onChange={onUpload} />
)}
{Boolean(values.length) && (
<div data-testid="handler">
<ValuesHandler values={values} />
</div>
)}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
现在我想测试values用户上传文件时设置是否正确,然后ValuesHandler显示在页面中。
我正在我的 App.test.tsx 中朝这个方向尝试
import user from '@testing-library/user-event';
import someValues from '../somefile.json';
import { …Run Code Online (Sandbox Code Playgroud) 一些背景:我有一个组件在加载时立即调用 useQuery 挂钩。当该查询运行时,我旋转一个加载微调器。一旦完成,我就会根据数据渲染内容。
我添加了一个useEffect挂钩来监视查询结果并记录数据,这就是我观察此问题的方式。
为了简化事情,它的工作原理如下:
export default function MyComponent(props: ???) {
const result = useQuery(INITIAL_DATA_QUERY, { variables: { id: 1 } });
React.useEffect(() => console.log(JSON.stringify({
loading: result.loading,
data: result.data,
error: result.error,
})), [result]);
if (result.loading) return <LoadingScreen message="Fetching data..."/>;
else if (result.error) return <ErrorPage/>
else return <Stuff info={result.data}> // omitted because it's unimportant to the issue
}
Run Code Online (Sandbox Code Playgroud)
当我在野外运行这个组件时,一切都完全按预期工作。它通过 Apollo 使用 GraphQL 到达端点,根据结果做出渲染决策等。
当我尝试模拟请求时,result.data和result.error字段永远不会改变,即使该result.loading字段发生了变化。我正在用来react-testing-library运行测试。
我的测试如下所示:
it("should load the data then render …Run Code Online (Sandbox Code Playgroud) 在我的 React 应用程序中,我有一个嵌入 Instagram 帖子的组件。
它呈现以下 HTML 结构:
<div data-testid="instagram"><iframe class="instagram-media instagram-media-rendered" id="instagram-embed-3" //etc....
Run Code Online (Sandbox Code Playgroud)
我正在使用React 测试库。
如何编写一个测试来检查iframe元素是否存在,例如使用 CSS 类instagram-media?
我的组件中有多个按钮,所有这些按钮都应该被禁用。
const buttons = screen.getAllByRole('button');
expect(ALL BUTTONS).toHaveAttribute('disabled'); // I want something like this.
Run Code Online (Sandbox Code Playgroud)
我们怎样才能以最方便的方式写这个呢?
javascript reactjs jestjs react-testing-library testing-library
我们注意到我们的单元测试执行速度非常慢,罪魁祸首似乎是getByRole查询按钮元素等。以下是今天给我们带来问题的查询示例:
userEvent.click(screen.getAllByRole('button', { name: 'Accept' })[0]);
Run Code Online (Sandbox Code Playgroud)
我们console.time()测量该查询的执行时间为 12782 毫秒。切换到getByText查询后需要 14 毫秒,这意味着getByRole花费了近 1000 倍的时间(!!!)。
我知道getByRole预计会运行得更慢,但这似乎有些极端。我在网上找到了一些线程,详细说明了某些测试如何花费了 5 倍的时间,但没有像这样的。作为选项添加hidden: true会加快速度,但速度不会太快。
我无法共享正在测试的代码,因为它是私有的。我不会将该组件描述为特别复杂,尽管它由一些较低级别的组件组成并使用模拟的网络请求。
是否有任何已知的原因导致像这样的查询运行缓慢,或者我们有什么方法可以在不牺牲所提供的信心的情况下加快执行速度getByRole?
我正在尝试在我的项目中使用反应测试库,但它对将主题传递给道具中的样式组件不满意,并且我收到此错误:“TypeError:无法读取未定义的属性”。完整的错误消息如下所示。
这是我正在测试的组件(一个非常简单的组件,因为我试图检查测试库是否正常工作):
import React from "react";
import styled from "styled-components/macro";
import { rem } from "polished";
import DoneIcon from "@mui/icons-material/Done";
const Flag = styled.div`
background-color: ${(props) => props.theme.colors.primary};
font-size: ${rem("14px")};
display: inline-flex;
align-items: center;
height: 32px;
border-radius: 16px;
padding: 0 12px 0 8px;
margin-bottom: ${rem("16px")};
color: #ffffff;
`;
const StyledDoneIcon = styled(DoneIcon)`
margin-right: 4px;
`;
const CompletionFlag = (props) => {
console.log("props: ", props);
return (
<Flag>
<StyledDoneIcon />
<span>Complete</span>
</Flag>
);
};
export default CompletionFlag;
Run Code Online (Sandbox Code Playgroud)
这是失败的测试(我还没有编写完整的测试,因为渲染抛出错误):
import { render …Run Code Online (Sandbox Code Playgroud) 问题:UserEvent.type不工作。我有一个简单的测试,我得到了文本框,它可以工作,但是当尝试在该文本框中键入时,文本不会显示。
我见过的大多数类似问题的解决方案都是等待打字。我试过了,文本仍然不显示。
版本:
"jest": "^28.1.3",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "12.1.2",
"@testing-library/user-event": "^14.2.1",
Run Code Online (Sandbox Code Playgroud)
测试:
test('LoginPage should handle events properly', async () => {
render(<LoginPage />)
const textbox = screen.getByRole(/textbox/i)
await userEvent.type(textbox, 'test')
screen.debug(textbox)
})
Run Code Online (Sandbox Code Playgroud)
screen.debug()触发打字后的输出:
<textarea
placeholder="enter your private key here."
/>
Run Code Online (Sandbox Code Playgroud)
登录页面组件:
import { useHistory } from 'react-router-dom'
import { useContext, useState, useEffect } from 'react'
import { ABOUT_URL } from '../../config'
import LoadingCover from '../../components/loadingCover/loadingCover'
import LoadingButton from '../../components/loadingButton/loadingButton'
import UserContext from '../../context/User'
const LoginPage …Run Code Online (Sandbox Code Playgroud) reactjs ×9
javascript ×3
jestjs ×3
react-hooks ×2
unit-testing ×2
apollo ×1
mocking ×1
react-hooks-testing-library ×1
react-router ×1
testing ×1