标签: react-native-testing-library

如何断言 React Native 测试库中的按钮被禁用?

如何断言 React Native 测试库中的按钮已禁用?我会想象这样的事情:

expect(getByRole('button')).toBeDisabled()
Run Code Online (Sandbox Code Playgroud)

但RNTL不提供toBeDisabled断言。

jestjs react-native react-native-testing-library

6
推荐指数
1
解决办法
5242
查看次数

如何使用react-native-testing-library提交表单或按输入键

我有以下问题:我需要测试在我的测试中是否调用了某个函数,但为了正确测试它,我需要按 Enter 或提交表单,但它似乎没有按预期工作。我已经尝试过以下操作:

\n
fireEvent.keyDown(input, { key: \'Enter\', code: \'Enter\' });\nfireEvent.submit(input);\n
Run Code Online (Sandbox Code Playgroud)\n

触发我的组件的 prop 的唯一方法onSubmitEditing是按 Enter 键。

\n

这是我正在尝试测试的代码:

\n
<Input placeholder="Cirurgi\xc3\xa3o"\n    testID=\'input_buscaCirurgiao_index\'\n    value={this.state.text}\n    autoCorrect={false}\n    keyboardType={(Platform.OS === \'android\') ? \'visible-password\' : \'default\'}\n    onChangeText={(item) => this.setState({ text: item })}\n    onSubmitEditing={() => { this._searchPressingEnter() }} // i need to test this\n    autoCapitalize=\'none\' \n/>\n
Run Code Online (Sandbox Code Playgroud)\n

这是该_searchPressingEnter函数的代码:

\n
_searchPressingEnter() {\n    Keyboard.dismiss()\n\n    let item = this.state.text\n\n    this._buscarCirurgioes(item)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

一旦按下 Enter 键,_searchPressingEnter就应该调用该函数,从而触发该onSubmitEditing道具。

\n

unit-testing react-native react-testing-library react-native-testing-library

6
推荐指数
1
解决办法
4405
查看次数

在 React Native 中使用钩子对我的功能组件进行单元测试的最佳实践是什么?

我已经围绕 ScrollView 编写了一个简单的包装组件,它根据给定的可用高度启用/禁用滚动:

import React, {useCallback, useEffect, useRef, useState} from 'react';
import {Keyboard, ScrollView} from 'react-native';
import {deviceHeight} from '../../../platform';

export default function ScrollingForm({
  availableHeight = deviceHeight,
  children,
}) {
  const [scrollEnabled, setScrollEnabled] = useState(true);
  const [formHeight, setFormHeight] = useState(0);
  const scrollingForm = useRef(null);

  const checkScrollViewEnabled = useCallback(() => {
    setScrollEnabled(formHeight > availableHeight);
  }, [availableHeight, formHeight]);

  const onFormLayout = async event => {
    await setFormHeight(event.nativeEvent.layout.height);
    checkScrollViewEnabled();
  };

  useEffect(() => {
    Keyboard.addListener('keyboardDidHide', checkScrollViewEnabled);

    // cleanup function
    return () => {
      Keyboard.removeListener('keyboardDidHide', …
Run Code Online (Sandbox Code Playgroud)

jestjs react-native react-native-testing-library

5
推荐指数
0
解决办法
516
查看次数

Jest Redux Persist:TypeError:无法在 writeStagedState 读取未定义的属性“catch”

我正在尝试使用 Jest 和 Typescript 测试我的 LoginScreen。我使用 redux 和 redux-persist 进行存储,并将存储设置为使用 AsyncStorage 作为配置的一部分。我怀疑 redux-persist 试图在它使用的内置超时功能用完并尝试将存储设置为默认存储后重新水合?我收到以下错误:

console.error
redux-persist: rehydrate for "root" called after timeout. undefined
undefined
at _rehydrate (node_modules/redux-persist/lib/persistReducer.js:70:71)
at node_modules/redux-persist/lib/persistReducer.js:102:11
at tryCallOne (node_modules/promise/setimmediate/core.js:37:12)
at Immediate._onImmediate (node_modules/promise/setimmediate/core.js:123:15)
Run Code Online (Sandbox Code Playgroud)

目前我的测试是这样的:

describe('Testing LoginScreen', () => {
  it('should render correctly', async () => {
    const { toJSON } = render(<MockedNavigator component={LoginScreen} />);
    await act(async () => await flushMicrotasksQueue());
    expect(toJSON()).toMatchSnapshot();
  });
});
Run Code Online (Sandbox Code Playgroud)

我的 MockNavigator 看起来像这样:

type MockedNavigatorProps = {
  component: React.ComponentType<any>;
  params?: {};
};

const Stack = …
Run Code Online (Sandbox Code Playgroud)

jestjs react-native redux-persist react-native-testing-library

5
推荐指数
1
解决办法
906
查看次数

如何在 React Native 测试库中通过辅助功能角色和标签选择元素

我的屏幕上有多个不同的按钮accessibilityLabel

<Button accessibilityLabel="First label">First</Button>
<Button accessibilityLabel="Second label">Second</Button>
Run Code Online (Sandbox Code Playgroud)

查询getByRole会忽略指定可访问性标签的第二个参数(在非本机测试库中可以正常工作)。

getByRole('button', { name: 'First label' })
Run Code Online (Sandbox Code Playgroud)

如何通过角色和标签查询元素?

jestjs react-native react-native-testing-library

5
推荐指数
0
解决办法
1153
查看次数

反应原生 jest.preset.js 文件丢失错误

我使用 @testing-library/react-native 来测试我的 RN 应用程序。当我运行 yarn test 时,出现以下错误。

@testing-library/react-native should have "jest-preset.js" or "jest-preset.json" file at the root.
Run Code Online (Sandbox Code Playgroud)

我为我的应用程序使用打字稿。

我的测试脚本是这样的。

test": "jest --config jest.config.json"
Run Code Online (Sandbox Code Playgroud)

jest.config.json 文件是这样的。

{
  "preset": "@testing-library/react-native",
  "collectCoverageFrom": ["src/**/*.{ts,tsx}"],
  "moduleDirectories": ["node_modules", "src"],
  "setupFiles": [
    "<rootDir>/jestSetup/setup.js",
    "./node_modules/react-native-gesture-handler/jestSetup.js"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?(react-native|@?react-navigation|@react-native-community))"
  ],
  "coveragePathIgnorePatterns": ["/node_modules/", "/jestSetup", "/src/config.ts", "/src/app.tsx"]
}
Run Code Online (Sandbox Code Playgroud)

为什么我收到这个错误?

reactjs jestjs react-native react-native-testing-library

5
推荐指数
1
解决办法
887
查看次数

当 TypeScript 阻止我时,如何向测试库的 React Native 组件添加 testId 属性?

我正在使用 TypeScript 编写 React Native 组件,并使用React Native 测试库对其进行测试。

我想在 React Native 组件上添加一个 testId 属性,如下所示:

<TextInput testId="foo" />
Run Code Online (Sandbox Code Playgroud)

然后在测试中引用它,如下所示:

it('receives a search string', () => {
  const { getByTestId } = render(<FooComponent />);;
  const textBox = getByTestId("foo");
  fireEvent.changeText(textBox,"some fake text");
  expect(textBox.value).toEqual("some fake text");
});
Run Code Online (Sandbox Code Playgroud)

但是 TypeScript 不允许我在组件上添加属性,因为当然,TypeScript 会向 React Native 询问有效属性,而 React Native 对;testId一无所知。testIdtestId 是@testing-library/react-native 的一部分。

如何让 TypeScript 识别添加的属性,例如testId@testing-library/react-native。

typescript react-native react-native-testing-library

5
推荐指数
1
解决办法
4660
查看次数

带有测试react-native-testing-library和jest-native的expo应用程序“没有导出成员'toHaveProp”

我正在尝试使用 jest-native 作为额外的匹配器,我认为我遇到了安装问题......
我正在使用 expo 的 React-native ts 应用程序,这是我的版本:

  • 世博会:“~39.0.0”
  • @testing-library/react-native版本:“^7.1.0”
  • 玩笑预设: '玩笑博览会',
  • 反应本机版本:“63.4”

我想以这种方式使用它:

import { toHaveProp } from '@testing-library/jest-native';

expect.extend({ toHaveProp });
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

Module '"../../../../../../node_modules/@testing-library/jest-native/extend-expect"' has no exported member 'toHaveProp'.
Run Code Online (Sandbox Code Playgroud)

任何想法 ?

typescript jestjs react-native react-native-testing-library

5
推荐指数
1
解决办法
3643
查看次数

使用 Jest 运行测试库/react-native 时,RNEncryptedStorage 未定义

react-native-testing-library我正在尝试使用Jest设置我的反应本机测试环境。我的反应本机应用程序使用react-native-encrypted-storage. 当我运行第一个示例测试(下面的代码)时,它失败并提示RNEcryptedStorage未定义。

import React from "react";
import "react-native";
// Note: test renderer must be required after react-native.
import renderer from "react-test-renderer";
import App from "../App";
    
it("renders correctly", () => {
    console.log("Rendering");
    renderer.create(<App />);
});
Run Code Online (Sandbox Code Playgroud)

完整错误:

RNEncryptedStorage 未定义

在对象。(node_modules/react-native-encrypted-storage/lib/commonjs/EncryptedStorage.ts:7:9) 在对象处。(node_modules/react-native-encrypted-storage/lib/commonjs/index.ts:1:1)

这是我第一次设置测试环境,所以不确定从哪里开始解决这个问题。

jestjs react-native react-native-testing-library

5
推荐指数
2
解决办法
5376
查看次数

使用反应测试库编写重新图表的单元测试

我正在为我们的 React 应用程序编写单元测试。使用 recharts 库创建的组件很少。

import { COLORS } from 'constants/colors.constants';
import { FC } from 'react';

import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { MonthlyApplication } from 'store/stats/types/stats-state.types';

const BarChartComponent: FC<BarChartComponentProps> = ({
  data,
  barSize,
  height,
  color,
  allowDecimals,
}) => (
  <ResponsiveContainer width='100%' height={height}>
    <BarChart data={data}>
      <CartesianGrid strokeDasharray='10 10 ' />
      <XAxis dataKey='month' />
      <YAxis allowDecimals={allowDecimals} />
      <Tooltip />
      <Bar dataKey='count' fill={color} barSize={barSize} />
    </BarChart>
  </ResponsiveContainer>
);

type BarChartComponentProps = {
  data: MonthlyApplication[]; …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-testing-library react-native-testing-library

5
推荐指数
1
解决办法
3350
查看次数