标签: react-testing-library

React Jest:从测试中触发“addEventListener”“消息”

我的 React 项目有一些代码用于监听消息事件。

const onMessage = ({ data }) => {
  console.log('On onMessage has been fired');
}

window.addEventListener('message', onMessage);
Run Code Online (Sandbox Code Playgroud)

有谁知道如何从我的测试套件中触发此事件?我尝试过诸如事件之类的库和许多诸如

test('Recieves message', async () => {
  //Some setup..

  //trigger the addEventListener('message')
  window.parent.postMessage('Hello', '*');  //doesn't work
  window.postMessage('Hello', '*'); //doesn't work
  const ee = new events.EventEmitter();
  ee.emit('Hello') //doesn't work

  //Some further tests...
})
Run Code Online (Sandbox Code Playgroud)

似乎什么都不起作用。请注意,我需要小心这个测试,我不会模拟并覆盖所有addEventListener. 我仍然需要核心代码来完成我想要做的事情。我只需要从我的测试中触发或发出消息事件

dom postmessage reactjs jestjs react-testing-library

7
推荐指数
2
解决办法
8301
查看次数

如何使用反应测试库测试临时加载文本?

我有一个表格,在处理时显示“正在提交”状态,在完成后显示“已提交”状态。

这是我正在使用的提交处理程序......

const handleSubmit = (e, _setTitle) => {
    e.preventDefault()
    _setTitle('Submitting...')
    try {
      doformStuff(emailRef.current.value)
    } catch (err) {
      throw new Error(err)
    } finally {
      _setTitle('Submitted perfectly.')
    }
  }
Run Code Online (Sandbox Code Playgroud)

我想测试提交状态是否出现,无论多短。

it('shows "submitting" when submitting', async () => {
    // arrange
    render(<MobileEmailCapture/>)
    // act
    const emailInput = screen.getByPlaceholderText('yourem@il.com')
    userEvent.type(emailInput, fakeEmail)
    fireEvent.submit(screen.getByTestId('form'))
    // assert
    expect(screen.getByTestId('title')).toHaveTextContent('Submitting...')
  })
Run Code Online (Sandbox Code Playgroud)

问题是测试直接跳转到提交状态 Error: FAILED Expected 'Submitted perfectly.' to match 'Submitting...'.

我知道这就是最终的结果,但我想测试临时过渡状态。我怎么做?

forms testing reactjs react-testing-library

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

React-testing-libary userEvent 悬停不起作用?

我尝试测试我的悬停是否有效,这是我要测试的代码

//styled components + typescript
const Info = styled.div`
    opacity: 0;
    width:100%;
    height: 100%;
    position: absolute;
    top:0;
    left:0;
    background-color: rgba(0,0,0,0.2);
    z-index:3;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.5s ease;
    cursor: pointer;
`
const Container = styled.div`
    flex:1;
    margin:5px;
    min-width:280px;
    height:350px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5fbfd;
    position: relative;

    &:hover ${Info}{
        opacity: 1;
    }
`
const ProductItem = ({item}:ProductItemProp) => {
    return (
        <Container data-testid="productContainer">
            <Circle/>
            <Image src={item.img}/>
            <Info data-testid="productInfo">
                <Icon data-testid="productIcon">
                    <ShoppingCartOutlined/>
                </Icon>
                <Icon>
                    <SearchOutlined/>
                </Icon> …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

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

仅当 '--module' 选项为 'es2020'、'esnext' 或 'system' 时,才允许使用 'import.meta' 元属性 Snowpack+testing-library

我在为 Snowpack 项目设置 Jest 和 React 测试库时遇到问题,想知道你们中是否有人遇到过类似的情况。所以我收到的错误是The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'指向 。const { SNOWPACK_PUBLIC_BASE_URL } = import.meta.env;我已按照所有文档正确设置配置,但仍然收到此错误。我的配置文件如下。

package.json:

{
    "jest": {
        "verbose": true,
        "preset": "ts-jest",
        "testEnvironment": "node",
        "transform": {
            "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest"
        },
        "transformIgnorePatterns": [
            "node_modules/(?!variables/.*)"
        ],
        "moduleNameMapper": {
            "@app/(.*)": "<rootDir>/src/$1",
            "@auth/(.*)": "<rootDir>/src/auth/$1",
            "@hooks/(.*)": "<rootDir>/src/hooks/$1",
            "@gtm/(.*)": "<rootDir>/src/gtm/$1"
        }
    },
    "scripts": {
        "start": "snowpack dev",
        "build": "snowpack build",
        "test": "jest __tests__/ --coverage",
        "test:watch": "jest --watch",
        "format": "prettier --write …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs jestjs react-testing-library snowpack

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

React-Bootstrap 无效表单反馈始终可见如何测试?

我无法使用 React-bootstrap 测试表单的正确验证。\n我想看到,当输入模式无效时,一旦验证表单,就会显示无效的反馈文本。

\n

带有测试的工作codesandbox:https://codesandbox.io/s/flamboyant-cerf-7t7jq

\n
import React, { useState } from "react";\n\nimport { Form, Button, InputGroup } from "react-bootstrap";\n\nexport default function App(): JSX.Element {\n  const [validated, setValidated] = useState<boolean>(false);\n\n  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    setValidated(true);\n  };\n\n  return (\n    <Form\n      className="col-12 col-lg-5 trans-form"\n      noValidate\n      validated={validated}\n      onSubmit={handleSubmit}\n    >\n      <InputGroup className="my-2">\n        <InputGroup.Prepend>\n          <InputGroup.Text>Receiver Public Key</InputGroup.Text>\n        </InputGroup.Prepend>\n        <Form.Control\n          role="textbox"\n          className="text-truncate rounded-right"\n          type="text"\n          pattern="[A-Za-z0-9]{5}"\n          required\n        />\n        <Form.Control.Feedback\n          className="font-weight-bold"\n          type="invalid"\n          role="alert"\n        >\n          Length or format are incorrect!\n        </Form.Control.Feedback>\n      </InputGroup>\n\n      <Button\n        role="button"\n …
Run Code Online (Sandbox Code Playgroud)

forms validation jestjs react-bootstrap react-testing-library

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

getByText 用于通过动态生成的字符串将文本拆分为单独的行

我有一个元素,其中静态和动态文本的组合都在同一行上。

当通过包含一些静态和动态文本的子字符串测试此行文本时,它失败,显示输出被分割成多行,并且在动态部分之前和之后进行分割。

到底是怎么回事?为什么我不能按照我期望的方式测试它?我该如何正确测试这个?

代码.jsx

const dynamicText = 'all be on one line';

return <div>This should {dynamicText} like I expect.</div>
Run Code Online (Sandbox Code Playgroud)

代码.spec.js

it('Should have dynamic text on one line', () => {
    const {getByText} = render(<Code />);

    expect(getByText('should all be on one line ')).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)

测试输出

Unable to find an element with the text: ... This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your …
Run Code Online (Sandbox Code Playgroud)

javascript testing unit-testing reactjs react-testing-library

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

React 测试库无法检查禁用按钮

我用来react-hook-form控制我的表单输入(ChakraUI 输入)并禁用“提交”按钮以防输入无效

由于我FormProvider在父组件中使用了多页表单,因此根据当前页面更改验证架构

   const currentValidationSchema = validationSchema[activeStep];

    const methods = useForm({
        mode: 'all',
        defaultValues: DEFAULT_VALUES,
        resolver: yupResolver(currentValidationSchema),
    });

Run Code Online (Sandbox Code Playgroud)
 <FormProvider {...methods}>
    <Box >{renderCurrentStep(activeStep)}</Box>
  </FormProvider>
Run Code Online (Sandbox Code Playgroud)

useFormContext并在子组件中使用它

    const {
        control,
        watch,
        getValues,
        clearErrors,
        setError,
        setValue,
        formState: { errors, isValid },
    } = useFormContext<IOrderProductFormData>();
Run Code Online (Sandbox Code Playgroud)
    <Controller
        control={control}
        name="phoneNumber"
        render={({ field: { onChange, value } }) => {
            return (
                <InputMask
                    mask="999 99 999"
                    onChange={onChange}
                    maskChar=" "
                    value={value}
                >
                    {(inputProps: any) => (
                        <InputGroup variant="phone">
                            <InputLeftAddon>+1</InputLeftAddon>
                            <Input
                                type="tel"
                                ref={inputRef}
                                aria-label="phone-number"
                                data-testid="phone-number" …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs react-testing-library

6
推荐指数
0
解决办法
1183
查看次数

React 测试库:在这种情况下如何使用屏幕而不是容器

在React测试库中,按照惯例,最好使用屏幕而不是从渲染中解构方法。

我有一个组件,我需要在其中测试渲染的文本。该组件中的顶级容器是 div,因此没有可访问的查询来获取文本匹配。如何使用屏幕进行文本匹配?

我目前已经求助于使用解构道具中的容器,然后在容器上进行文本匹配。

// MyComponent - simplified
const MyComponent = () => <div> some text </div>

// test
const { container } = render(<MyComponent />);
expect(container).toHaveTextContent(...)

Run Code Online (Sandbox Code Playgroud)

参考: https: //kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-screen

在博客文章中提到,解构主要是为了遗留目的而支持的,但没有任何用例不能使用屏幕来解决。这个用例可以使用屏幕来解决吗?

reactjs react-testing-library testing-library

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

测试未包含在 act(...) 中

我遇到了一个奇怪的问题,非常感谢这里的帮助。我按照这里的例子,不知道到底发生了什么。警告不应该出现,对吧?

组件:Hello.tsx

import React, { useEffect, useState } from "react"

export default () => {
  const [loaded, setLoaded] = useState("false")

  useEffect(() => {
    async function load() {
      await Promise.resolve()
      setLoaded("true")
    }
    load()
  }, [])

  return loaded ? <div>loaded</div> : <div>loading...</div>
}
Run Code Online (Sandbox Code Playgroud)

测试:

import { render } from "@testing-library/react"
import Hello from "./hello"

test("React Testing Library works!", () => {
  render(<Hello />)
})
Run Code Online (Sandbox Code Playgroud)

测试通过,但我在控制台中看到警告:

Warning: An update to _default inside a test was not wrapped in act(...).
    
    When …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

如何使用 React 测试库测试输入?

我正在尝试通过 React 测试库测试组件input的值Search。

搜索组件接收两个属性:handleChange和input value: title。

我的目标是编写测试,以便最初输入值为空,当用户键入内容时,测试可以验证监听事件值是否正确,但它始终获取初始值。

我试图在键入之前清除输入,但它不起作用。

错误是:

 Expected the element to have value:
                       // indicates as empty string which I expect
                    
    Received:
      test            // it is still the default value: `test`, UserEvent.clear didn't clear
Run Code Online (Sandbox Code Playgroud)

这是两个测试,首先检查输入最初是否为空,这工作正常,第二个测试监听输入。

import { fireEvent, screen, waitFor } from "@testing-library/react";
import Search from "../Search";
import { render } from "../../../test-utils/test-utils";
import "@testing-library/jest-dom";
import userEvent from "@testing-library/user-event";

const mockedOnChange = jest.fn();

describe("input should be filled with title", …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs jestjs react-testing-library

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