我正在尝试测试反应组件并使用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
我正在使用玩笑测试来测试用 Create React App 创建的 #typescript 编写的 React 项目。我在用着react-testing-library。我有一个表单组件,它显示alert表单是否提交为空。我想通过监视/嘲笑来测试此功能(也许),window.alert但它不起作用。
我尝试jest.fn()按照许多答案中的建议使用,但这也不起作用。
window.alert = jest.fn();
expect(window.alert).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)
这是我的实现方式:Form.tsx
async handleSubmit(event: React.FormEvent<HTMLFormElement>) {
// check for errors
if (errors) {
window.alert('Some Error occurred');
return;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我构建 React+Jest+react-testing-library 测试的方法:Form.test.tsx
it('alerts on submit click', async () => {
const alertMock = jest.spyOn(window,'alert');
const { getByText, getByTestId } = render(<Form />)
fireEvent.click(getByText('Submit'))
expect(alertMock).toHaveBeenCalledTimes(1)
})
Run Code Online (Sandbox Code Playgroud) I have looked into similar questions (like this one), but the proposed solutions didn't work for me when using react-testing-library.
I have a component that can receive multiple children. This component will then calculate its own size and its children size, to check how many children it will be able to render. It works fine when I use it in my application.
My problem is that, when rendering this component with react-testing-library, the container of the component …
我正在尝试使用测试库在 fireEvent.click 之后检查 DOM 元素。我知道我需要在 fireEvent 之后等待,但不知道为什么简单地使用 await 不起作用?下面是用两种方式编写的相同测试——第一个失败,第二个通过。我不明白为什么第一个失败......非常感谢任何见解!
ps——我知道wait已被弃用,waitFor是首选,但是由于一些限制,我目前无法更新版本:(
失败的测试
// This test fails with the following error and warning:
// Error: Unable to find an element by: [data-test="name_wrapper"]
// Warning: An update to OnlinePaymentModule inside a test was not wrapped in act(...).
it('this is a failing test...why', async () => {
const { getByText, getByTestId } = render(<Modal {...props} />);
const button = getByText('open modal');
fireEvent.click(button);
const nameWrapper = await getByTestId('name_wrapper');
expect(
nameWrapper.getElementsByTagName('output')[0].textContent
).toBe('Jon Doe');
const numberWrapper = …Run Code Online (Sandbox Code Playgroud)问题: 我有多个下拉菜单,我正在检查其中是否有任何一个打开。我如何在 React 测试库中做到这一点?(我正在浏览一堆 tabIndexes 并检查它们)
问题: container.querySelectorAll 在反应测试库中是不可能的。
代码:
it('should not expand dropdown for multiple view', () => {
const { container } = render(
getMockedComponent()
)
expect(container).toBeVisible()
container
.querySelector('div[tabindex]').forEach(eachAccordian => {
expect(eachAccordian).toHaveAttribute('aria-expanded', 'false')
})
})
Run Code Online (Sandbox Code Playgroud)
如何使用 React 测试库检查所有节点?
我有一个相当复杂的上下文,我将其包装在我的应用程序中来处理身份验证并提供从身份验证服务检索到的关联数据。我想绕过提供程序的所有功能并仅模拟返回值。当上下文呈现时,它会执行一堆我在测试时不希望发生的初始化函数。
我在我的包装函数中尝试了类似的方法:
const mockValue = {
error: null,
isAuthenticated: true,
currentUser: 'phony',
login: jest.fn(),
logout: jest.fn(),
getAccessToken: jest.fn(),
}
const MockAuthContext = () => ( React.createContext(mockValue) )
jest.mock("../contexts/AuthContext", () => ({
__esModule: true,
namedExport: jest.fn(),
default: jest.fn(),
}));
beforeAll(() => {
AuthContext.mockImplementation(MockAuthContext);
});
const customRender = (ui, { ...renderOpts } = {}) => {
const ProviderWrapper = ({ children }) => (
<AuthContext.Provider>
{children}
</AuthContext.Provider>
);
return render(ui, { wrapper: ProviderWrapper, ...renderOpts });
};
// re-export everything
export * from …Run Code Online (Sandbox Code Playgroud) 我想使用 @testing-library/react-hooks 中的 renderHook 来测试组件的状态更新,这让我们可以像在 React 功能组件中一样渲染钩子。只是想知道,这是否仅适用于自定义挂钩,因为当我尝试使用此方法来测试组件时状态没有改变
it('test count update', () => {
const { result } = renderHook(() => useState({ count: 0 }));
const [state, setState] = result.current;
const wrapper = mount(<ComponentToTest />);
act(() => {
wrapper.find('button').simulate('click');
})
expect(state).toBe({ count: 1 });
})
Run Code Online (Sandbox Code Playgroud)
由于计数未更新且仍为 0,因此出现错误
有人可以帮忙吗

我有一个搜索框组件:
function SearchBox({ search, setSearch }) {
return (
<div>
<div>
<input onChange={e => setSearch(e.target.value)} type="text" placeholder="Search..." value={search} />
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
describe('Input value', () => {
it('updates on change', () => {
const { queryByPlaceholderText } = render(<SearchBox />)
const searchInput = queryByPlaceholderText('Search...')
fireEvent.change(searchInput, { target: { value: 'test' } })
expect(searchInput.value).toBe('test')
})
})
Run Code Online (Sandbox Code Playgroud)
但后来我得到一个错误:
错误:未捕获 [TypeError:setSearch 不是函数]
我可以如何测试此 SearchBox 组件以及测试什么内容?
我正在尝试使用 jest 和 React 测试库编写一个测试,以查看商店是否更新状态以及新状态是否显示在组件内。
我有一个像这样的组件:
import { getName } from 'src/store/actions/hello/getName';
const HelloComponent = () => {
const dispatch = useDispatch();
const { name, isLoading } = useSelector((state:RootState) => state.Hello)
useEffect( () => {
dispatch(getName());
}, []);
return (
<div>
{ name &&
Hello {name}
}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
有一个商店调用如下 API:
const getName = () => (dispatch) => {
const URL = getUrl()
fetch(URL, {method: 'GET'})
.then((response) => response.json())
.then(({ data }) => dispatch({
type: 'SAVE_NAME',
payload: data.name
})) …Run Code Online (Sandbox Code Playgroud) 为什么 RTL 将隐藏元素显示为可见?
expect(screen.queryByText(/months in operation\?/i)).not.toBeVisible()
Run Code Online (Sandbox Code Playgroud)
Received element is visible: <label aria-hidden="true" for="monthsDropdown" />
expect(screen.queryByText(/months in operation \?/i)).not.toBeInTheDocument()
Run Code Online (Sandbox Code Playgroud)
expected document not to contain element, found <label aria-hidden="true" for="monthsDropdown">Months in operation?</label> instead
该标签的父div也有display:none;的样式。可见性:隐藏;高度:0;
这是预期的行为吗?
reactjs ×10
jestjs ×7
javascript ×2
arrays ×1
async-await ×1
jsdom ×1
mocking ×1
react-hooks ×1
redux ×1
typescript ×1
unit-testing ×1