标签: react-testing-library

反应本机无法找到具有 testID 的元素

我收到此错误:

Unable to find an element with the testID of: input-text

输入.js:

import React from "react";
import { View, StyleSheet } from "react-native";
import { Text, TextInput } from "react-native-paper";

const Input = (props) => {
  return (
    <View>
      <TextInput
        name={props.name}
        keyboardType={props.keyboardType}
        value={props.value}
        label={props.label}
        mode="outlined"
        onChange={(newVal) => props.onChange(props.name, newVal)}
        required={props.required}
        data-testid="input-text"
      />
      <Text>{props.errors}</Text>
    </View>
  );
};

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

输入 test.js:

import React from "react";
import { Input } from "../components/common";

import { render, fireEvent } from "@testing-library/react-native"; …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-native react-testing-library

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

如何在 React 中使用 Enzyme 或 React 测试库测试 Material-UI 的响应式 UI(例如隐藏、网格、断点)

如何在 Material-UI 中测试响应式元素?

例子:

import React from "react";
import Hidden from "@material-ui/core/Hidden";

const HideOnMobile = (props) => {
  return <Hidden xsDown>{props.children}</Hidden>;
};
Run Code Online (Sandbox Code Playgroud)

测试用例:

describe(HideOnMobile, () => {
  describe("when screensize is sm", () => {
    it("shows children", () => {});
  });

  describe("when screensize is xs", () => {
    it("hides children", () => {});
  });
});
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs material-ui enzyme react-testing-library

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

通过 React 测试库 (RTL) 触发 react-ace onChange

在我的代码中,我有使用 react-ace 的组件。在我的渲染函数中,我有这一行:

<CodeEditor onChange={onCodeChanged} value={code} />
Run Code Online (Sandbox Code Playgroud)

回调函数:

const onCodeBodyChanged = (newCode) => {
      // some code ...
      dispatch(setResource({ newCode }));
}
Run Code Online (Sandbox Code Playgroud)

我想onCodeChanged通过 RTL进行测试,所以我试图找到更改值的文本区域,但没有任何成功

(不工作)测试的例子:

      const { container } = render(<ResourceEditorPanel />, createMockStore());
      const ace = container.querySelectorAll('.ace_text-input');
      fireEvent.change(ace, { target: { value: 'someText' } });
      await waitFor(() => {
        expect(dispatch).toHaveBeenCalled();
      });

Run Code Online (Sandbox Code Playgroud)

问题是fireEvent.change(ace, { target: { value: 'someText' } });不会触发我的功能 - onCodeChanged。

你知道我该如何测试吗?

ace-editor reactjs react-ace react-testing-library

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

测试特定的 MaterialUI 图标

是否可以在特定的 Material UI 图标中作为 ArrowLeft / ArrowRight 而不是 .MuiSvgIcon-root 进行测试?

应用组件:

return {open ? <ArrowLeft/> :<ArrowRight/>}
Run Code Online (Sandbox Code Playgroud)

RTL 测试:下面的测试正在通过,但它不会检查特定的 ArrowLeft 或 ArrowRight 图标。

describes("MockTest",()=>{

it("renders Left arrow",()=>{
const {container} = renders(<App open={true}/>);
expect(container.querySelector(".MuiSvgIcon-root").toBeTruthy();
});

it("renders Right arrow",()=>{
const {container} = renders(<App open={false}/>);
expect(container.querySelector(".MuiSvgIcon-root").toBeTruthy();
});

});

Run Code Online (Sandbox Code Playgroud)

reactjs jestjs material-ui react-testing-library

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

React - Jest RTL 检查元素是否不可见

我有一个直接的反应补偿。我想根据反应状态测试样式。该 comp 如下所示:

反应补偿。

const Backdrop = ({ showBackdrop }) => {
    const backdropRef = useRef();

    function getBackdropHeight() {
        if (typeof window !== 'undefined') {
            return `calc(${document.body.clientHeight}px -
            ${backdropRef.current?.offsetTop || 0}px)`;
        }

        return 0;
    }

    return (
        <div
            data-testid="backdrop"
            className={classNames(styles.backdrop, showBackdrop ? styles.show : styles.hide)}
            ref={backdropRef}
            style={{ height: getBackdropHeight() }}
        />
    );
};
Run Code Online (Sandbox Code Playgroud)

造型

.backdrop {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 156px;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 3;
    ...
}

.show {
    opacity: 0;
    visibility: …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-test-renderer react-testing-library

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

期望在反应测试库中使用参数调用 jest mock 失败

我希望这个测试通过,但它失败了:

it('should consume files on drop', () => {
  const mock = jest.fn();
  const file = new File(['file'], 'file.txt', { type: 'text/plain' });
  const fileList = [file];

  render(<DropZone onDocumentDrop={mock} />);

  const dropZone = screen.getByTestId('dropZone');
  const dropEvent = createEvent.drop(dropZone);

  Object.defineProperty(dropEvent, 'dataTransfer', {
    value: {
      files: {
        item: (index: number) => fileList[index],
        length: fileList.length,
      },
    },
  });

  fireEvent(dropZone, dropEvent);

  expect(dropZone).toBeInTheDocument();
  expect(mock).toHaveBeenCalled();
  expect(mock).toHaveBeenCalledWith({
    item: (index: number) => fileList[index],
    length: 1,
  });
});
Run Code Online (Sandbox Code Playgroud)

Jest 报告说:

expect(jest.fn()).toHaveBeenCalledWith(...expected)

- Expected
+ Received

- {"item": [Function item], …
Run Code Online (Sandbox Code Playgroud)

file-upload mocking reactjs jestjs react-testing-library

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

How to test if element exists?

I want to check if inside my component exists a button.

import React, {useState} from 'react';

const Text = ({text}) => {
    const [state, setState]= useState(0);

    const add  = () => {
        setState(state+1)
    };

    return (
        <div>
            <h1>Hello World</h1>
            <h2>Hello {text}</h2>
            <h2>Count {state}</h2>
            <button role="button" onClick={add}>Increase</button>
        </div>
    );
};

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

For that test i created:

test('check counter', ()=> {
    const { getByText } = render(<Text />);
    const button = getByText("Increase");
    expect(button.toBeTruthy())
});
Run Code Online (Sandbox Code Playgroud)

After running the test i get …

reactjs react-testing-library

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

expect(...).toHaveAttribute 不是函数 - 为什么?

我创建了一些基本测试并遵循 Jests 网站上的入门指南,但 toHaveAttribute 显然不是一个函数

import React from "react";
import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { App } from "../App";

test("allows users to add items to their list", () => {
  const { getByText, getByLabelText, getByTestId } = render(<App />);

  const input = getByLabelText("What needs to be done?");
  userEvent.type(getByTestId("email"), "Hello World!")
  expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
})
Run Code Online (Sandbox Code Playgroud)

类型错误:expect(...).toHaveAttribute 不是函数

  10 |   const input = getByLabelText("What needs to be done?");
  11 |   userEvent.type(getByTestId("email"), "Hello World!")
> 12 …
Run Code Online (Sandbox Code Playgroud)

testing unit-testing reactjs jestjs react-testing-library

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

在 React 测试库中测试点击事件

这是一个简单的子组件,它answer在单击按钮时显示问题:

const Question = ({ question, answer }) => {
    const [showAnswer, setShowAnswer] = useState(false)
    return (
        <>
           <article>
               <header>
                    <h2 data-testid="question">{question}</h2>
                    <button onClick={() => setShowAnswer(!showAnswer)}>
                        {
                            !showAnswer ? <FiPlusCircle /> : <FiMinusCircle />
                        }
                    </button>
               </header>
               {
                   showAnswer && <p data-testid="answer">{answer}</p>
               }
           </article>
        </>
    )
}

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

我试图测试当button点击 时,onClick附加的被调用一次并且 a<p>元素出现在屏幕上:

const onClick = jest.fn()

test('clicking the button toggles an answer on/off', () => {
    render(<Question />);
    
    const button = …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

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

如何用玩笑正确模拟`antd`上传拖动器?

我的项目中有以下反应代码

import React from 'react';
import { Upload } from 'antd';

const { Dragger } = Upload;

...

<Dragger
  accept={ACCEPTED_FORMATS}
  beforeUpload={beforeUpload}
  data-testid="upload-dragger"
  maxCount={1}
  onChange={({ file: { status } }) => {
    if (status === 'done') onUploadComplete();
  }}
  progress={progress}
  showUploadList={false}
>
{/* here i have a button, code ommited for clarity, if needed i'll post it */}
</Dragger>
Run Code Online (Sandbox Code Playgroud)

我想测试onUploadComplete()当 file.status 为 时是否调用了回调函数'done'。

这是我现在进行测试的方式:

  1. 我有一个 jest.mock 来模拟一个永远成功的愚蠢请求
import React from 'react';
import { Upload } from 'antd'; …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs antd react-testing-library

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