标签: react-native-testing-library

带有反应本机测试库的样式组件主题

我已经被困了一段时间,试图弄清楚我到底做错了什么,我觉得我已经尝试了我找到的所有解决方案,但它不起作用。为了描述正在发生的事情,我制作了最简单的组件来展示正在发生的事情。

这是我的主题

export default const theme = {
    colors: {
        white: '#FFFFFF',
        black: '#000',
        lightGray: '#f0f2f1',
        darkGray: '#909190',
        primaryColor: '#007772',
        secondaryColor: '#0775BC',
        textColor: '#231F20',
        lightPrimary: '#DBFFFF',
        red: '#B80F0A',
        primaryHalf: '#7FBAB8',
    },
    font: {
        family: 'Nunito-Regular',
    },
};
Run Code Online (Sandbox Code Playgroud)

这是我的组件

import React from 'react';
import styled from 'styled-components/native';

const Wrapper = styled.View`
    background-color: ${(props) => props.theme.colors.white};
`;

const TestSimpleComponent: React.FC = ({ children }) => {
    return <Wrapper>{children}</Wrapper>;
};

export default TestSimpleComponent;
Run Code Online (Sandbox Code Playgroud)

非常简单,只是用来自主题的白色背景包裹一些东西。

最后,这是我的简单测试

import React from 'react';
import { Text } …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-native styled-components react-native-testing-library

4
推荐指数
1
解决办法
2056
查看次数

IDE 无法识别 Jest 及其功能

我有一个基本的反应本机/博览会模板应用程序。我已经在开发依赖项中添加了jest-expo和,并且还更新了 package.json,如用于测试的 expo 文档中记录的那样。react-test-renderer

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    ...
    "test": "jest"
  },
  "dependencies": {
    "expo": "~41.0.1",
    ...
    "react": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@testing-library/jest-native": "^4.0.1",
    "@testing-library/react-native": "^7.2.0",
    "jest-expo": "^41.0.0",
    "react-test-renderer": "^17.0.2"
  },
  "private": true,
  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ],
    "setupFilesAfterEnv": [
      "@testing-library/jest-native/extend-expect"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我还添加了React Native Testing Library测试 UI 的功能。并且测试运行良好。

但问题是 WebStorm IDE 无法识别 Jest 及其功能。

在此输入图像描述

在此输入图像描述

你能帮我解决这个问题吗?

更新

根据评论,我尝试通过“设置”配置安装 Typescript Jest 类型定义,并尝试使用“yarn/npm”进行安装。但这没有帮助。

在此输入图像描述

另一个更新

但是,如果我取消选中项目的 node_modules …

webstorm jestjs react-native expo react-native-testing-library

4
推荐指数
1
解决办法
1734
查看次数

玩笑模拟尺寸没有改变

我是第一次进行测试,所以我非常确定我做错了什么。

我正在编写测试用例,我的组件在内部执行此操作。

const {width, height} = Dimensions.get('window')
Run Code Online (Sandbox Code Playgroud)

对于我的测试用例,我考虑的是 iPhone 11,其尺寸为width: 414, height:896,并且我希望所有测试用例的尺寸保持一致。

在测试时响应本机测试库,将宽度设置为750,高度设置为1334

我想更改为iPhone 11尺寸,我在网上搜索了一些用于jest.mock更改功能的文章。

所以我做了这样的事情

it('renders correctly', () => {
     jest.mock("Dimensions", () => ({
        get: jest.fn().mockReturnValue({ width: 414, height:896 }),
     }))
      
     const {getByTestId} = render(<Home />)
 
Run Code Online (Sandbox Code Playgroud)

Home组件有console.log(width, height),但它仍然给出宽度为 750,高度为 1334(因此我的测试用例失败)。

我该如何修复它?

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

4
推荐指数
1
解决办法
4361
查看次数

React-query 如何在 Jest 测试中从自定义 useMutation 挂钩调用 mutate

我正在运行一个 React Native 项目,在其中测试用 React-query 编写的自定义钩子。我正在使用 Jest、@testing-library/react-hooks 和 @testing-library/react-native。在我的测试中,我似乎找不到调用钩子返回的 mutate 函数的方法。

看一下自定义钩子:

    export default function useAuthentication() {
      const { mutate, data, isSuccess, isError } = useMutation(
        authenticationApi.authenticateUser
      );
      return { mutate, data, isSuccess, isError };
    }
Run Code Online (Sandbox Code Playgroud)

根据react-query的文档,我使用 renderHook() 渲染钩子并等待突变调用的结果:

    const authBody: AuthBody = {
      username: '111111',
      password: '111111',
    };
    
    describe('Authentication Hook', () => {
      const sanityCall = () =>
        axios.post('http://localhost:4000/auth/authenticate');
      console.log(sanityCall());
    
      const queryClient = new QueryClient();
      it('Gets authentication data', async () => {
        const wrapper = ({ children }: any) …
Run Code Online (Sandbox Code Playgroud)

jestjs react-native react-hooks react-native-testing-library react-query

3
推荐指数
1
解决办法
8819
查看次数

在 FlatList 中测试 onScroll 事件

我一直在尝试使用这个非常简单的测试文件来测试onScrolla 的事件:FlatList

测试文件:

// @ts-nocheck
import React from 'react';
import { fireEvent, render } from '@testing-library/react-native';
import { MyComponent } from '../../../src/modules/MyComponent';

describe('MyComponent', () => {
  it('should not call if IS_IOS is false', async () => {
    const { debug, getByTestId } = render(<MyComponent/>);

    fireEvent(getByTestId('alpha'), 'onScroll', {
      nativeEvent: {
        contentSize: { height: 600, width: 400 },
        contentOffset: { y: 150, x : 0 }
      }
    })

    debug();
  });
});
Run Code Online (Sandbox Code Playgroud)

正在测试的组件:

import React from 'react';
import { FlatList, …
Run Code Online (Sandbox Code Playgroud)

javascript react-native react-native-testing-library

3
推荐指数
1
解决办法
5620
查看次数

简单玩笑测试中返回值无效

我正在测试 React Native 0.68.2/jest 29.0 的组件视图Home。简单的测试用例是从 jest doc 复制的:

\n
import React from 'react';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { render, cleanup, screen, fireEvent } from "@testing-library/react-native";\nimport App from '../App';\n\ndescribe ('App ', () => {\n    //afterEach(cleanup);\n    test ('shall stack screens', async () => {\n        const component = (<NavigationContainer>\n                             <App />\n                            </NavigationContainer>);\n        const {getByText} = render(component);\n\n        await waitFor(() => getByText('AppSplash'));\n        \n\n    })\n})\n
Run Code Online (Sandbox Code Playgroud)\n

这是 App.js:

\n
 import React, {useState, useContext, Component} from 'react';\n import { NavigationContainer } from '@react-navigation/native';\n …
Run Code Online (Sandbox Code Playgroud)

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

3
推荐指数
1
解决办法
5731
查看次数

开玩笑+反应导航未定位路线/参数

我正在尝试使用反应导航为应用程序编写测试,但遇到了正确读取路线和参数的问题。

我收到一个错误

类型错误:无法读取未定义的属性“params”

const [leadId] = useState(route.params.leadId);

我的组件看起来像

export default function AComponent() {
  const route = useRoute();
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const [leadId] = useState(route.params.leadId);
}
Run Code Online (Sandbox Code Playgroud)

我已尝试遵循https://callstack.github.io/react-native-testing-library/docs/react-navigation/Warning: React.createElement: type is invalid但在包装组件时收到了。

我的测试看起来像

import React from 'react';
import { Provider } from 'react-redux';
import { NavigationContainer } from '@react-navigation/native';
import { render, fireEvent, cleanup } from 'react-native-testing-library';
import configureMockStore from 'redux-mock-store';

import AComponent from 'components/contact/AComponent';

const mockStore = configureMockStore([]);

describe('<AComponent />', () => …
Run Code Online (Sandbox Code Playgroud)

javascript jestjs react-native react-navigation react-native-testing-library

2
推荐指数
1
解决办法
5836
查看次数

使用 Formik 和 Yup 作为验证模式时 React Native 测试失败

我正在尝试为使用 Formik 构建的 React Native 组件编写一些测试。这是一个简单的表单,要求输入用户名和密码,我想使用使用 Yup 构建的验证模式。

当我使用模拟器并手动测试表单时,表单的行为符合预期,仅当输入值无效时才会显示错误消息。

但是,当我尝试使用 编写一些自动化测试时@testing-library/react-native,其行为并不是我所期望的。即使提供的值有效,错误消息也会在测试中显示。下面是代码:

// App.test.js
import React from 'react';
import { render, act, fireEvent } from '@testing-library/react-native';

import App from '../App';

it('does not show error messages when input values are valid', async () => {
  const {
    findByPlaceholderText,
    getByPlaceholderText,
    getByText,
    queryAllByText,
  } = render(<App />);

  const usernameInput = await findByPlaceholderText('Username');
  const passwordInput = getByPlaceholderText('Password');
  const submitButton = getByText('Submit');

  await act(async () => {
    fireEvent.changeText(usernameInput, 'testUser');
    fireEvent.changeText(passwordInput, 'password');
    fireEvent.press(submitButton);
  });

  expect(queryAllByText('This …
Run Code Online (Sandbox Code Playgroud)

reactjs react-native yup formik react-native-testing-library

2
推荐指数
1
解决办法
2796
查看次数

为什么我无法安装 React Native 测试库?

我是应用程序测试的新手,从昨天开始深入研究这个主题。我想为我的 React Native 应用程序编写测试,并尝试使用以下命令安装React Native 测试库:

npm install --save-dev @testing-library/react-native @testing-library/jest-native
Run Code Online (Sandbox Code Playgroud)

然后我遇到了以下问题:

在此输入图像描述

我试图在谷歌中找到这个问题的解决方案,但没有成功。据我了解,问题出在依赖关系上?请告诉我在这种情况下我能做什么?

PS 我尝试使用 expo init 创建一个完全干净的项目,尝试安装该库,但得到了完全相同的错误

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

2
推荐指数
1
解决办法
1130
查看次数

编写一个单元测试来检查应用程序是否在react-native中离线

我有以下组件,如果应用程序离线,它会在应用程序上显示文本。

\n
import React from 'react';\n\nimport { useNetInfo } from '@react-native-community/netinfo';\n\nimport { Label } from 'components/ui';\n\nconst OfflineNotice = () => {\n  const netInfo = useNetInfo();\n\n  if (netInfo.type !== 'unknown' && netInfo.isInternetReachable === false) {\n    return <Label size={18} text='No Internet Connection' />;\n  }\n\n  return null;\n};\n\nexport default OfflineNotice;\n
Run Code Online (Sandbox Code Playgroud)\n

我想为此编写一个单元测试来检查它是否正常工作。我该怎么做?\n我是单元测试新手。我不明白如何嘲笑这个。

\n

我使用打字稿和测试库/反应本机。

\n

更新: \n为什么第一次测试失败?它不应该为空。但它失败了。错误是,

\n
OfflineNotice component \xe2\x80\xba test\n\nexpect(received).not.toBeNull()\n\nReceived: null\n\n  15 | \n  16 |     const { queryByText } = render(<OfflineNotice />);\n> 17 |     expect(queryByText(/no internet connection/i)).not.toBeNull();\n     |                                                        ^\n  18 …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-native react-native-community-netinfo react-native-testing-library

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

React Native 单元测试 - 无法访问未安装的测试渲染器上的 .root

您好,我正在使用react-native-testing-library 测试我的应用程序。当我运行测试返回测试失败时我该如何解决这个问题?错误是:

\n
Can't access .root on unmounted test renderer\n    \nThere seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.\nPlease check if you are using compatible versions of React Native and React Native Testing Library.\n    \nCan't access .root on unmounted test renderer\n
Run Code Online (Sandbox Code Playgroud)\n
\n

反应版本:"react": "18.2.0"

\n

反应本机版本:"react-native": "0.72.3"

\n

React Native 测试库版本:"@testing-library/react-native": "^12.2.2"

\n

测试库 Jest Native 版本:"@testing-library/jest-native": "^5.4.3"

\n
\n

我有这个测试代码;

\n
describe('LoginScreen', () => {\n …
Run Code Online (Sandbox Code Playgroud)

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

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