标签: react-testing-library

如何测试具有相同起点和终点的动画?

我有一个组件,当animatedprop 设置为 true时会“震动” 。这是它的样子

const Shake = ({ animate, children, ...props }) => {
  const { x } = useSpring({
    from: { x: 0 },
    x: animate ? 1 : 0,
    config: { mass: 12, tension: 500, friction: 80 },
  });
  return (
    <animated.div
      style={{
        transformOrigin: 'center center',
        transform: animate && x
          .interpolate({
            range: [0, 0.5, 1],
            output: [0, 2, 0],
          })
          .interpolate((x) => `rotate(${x}deg)`),
      }}
      {...props}
    >
      {children}
    </animated.div>
  );
};
Run Code Online (Sandbox Code Playgroud)

我之前测试过的动画或多或少只是从一种状态转换到另一种状态,比如从 0 到 1 的不透明度。用 react-testing-library …

reactjs jestjs react-spring react-testing-library

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

React 测试库中的“HTMLElement”类型不存在属性“value”

我正在使用 React-testing-library 并在最后一行出现错误: expect (title.value).toBe("testtitle");})})。错误消息是属性 'value' 在类型 'HTMLElement' 上不存在。如何纠正此错误消息以有效地编写此代码?

测试文件

  <Router history={history}>
            <Route render={(props) => 
            <NewQuestion {...props} onSave={jest.fn()}/>}/>
        </Router>)
    const title= getByPlaceholderText("What's your question? Be specific");
    fireEvent.change(title, {target: {value: "testtitle"}})
    expect (title.value).toBe("testtitle");})})
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript reactjs react-testing-library

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

使用 jest.mock('axios') 时如何模拟拦截器?

使用 jest 运行测试时,我有基本的测试服语法:

jest.mock('axios');

describe('app', () => {
    let render

    beforeEach(() => {
        axiosMock.get.mockResolvedValueOnce({
            data: {greeting: 'hello there'},
        }),
        render= renderApp()
    });

    test('should render something', () => {
        expect(something).toBeInTheDocument();
    });


});
Run Code Online (Sandbox Code Playgroud)

问题是我的代码中有拦截器,当使用 jest 命令输出运行测试时:

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

并指向拦截器对象

axiosInstance.interceptors.request.use(...

axiosInstance 是存储返回的变量 axios.create

export const axiosInstance = axios.create({...

在 SO How do I test axios in jest上参考了这个 axios 线程,但它不涉及任何拦截器,所以并没有真正的帮助。

reactjs jestjs axios react-testing-library

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

使用 Jest 和 React 测试库测试 `img.onLoad`/`img.onError`

今天下午,Out 团队在使用 Jest 为我们的<Avatar />组件编写 React 测试库 (RTL) 测试时遇到了一个场景。具体来说,我们想测试<img />标签是否在加载失败(onError被触发)以匹配预期的组件最终视图时从 DOM 中删除。出于某种原因,fireEvent在<img />DOM 元素上使用对我们来说并不是很明显,我们没有在网上找到这个明确的解决方案,所以我们想分享一下。可以想象,这也适用于其他事件onLoad。更多关于 RTL 事件。

it('should render with only initials when avatar image is NOT found', async() => {
  const { container } = render(<Avatar {...defaultMocks} />);
  const avatarImg = container.querySelector('img');

  expect(avatarImg).toBeInTheDocument();

  fireEvent(avatarImg, new Event('error'));

  expect(avatarImg).not.toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)

javascript jestjs react-testing-library

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

为什么在测试期间 useParams 在带有包装器的测试环境中返回未定义?

我现在已经在 2 个不同的代码库中看到了这一点,但我很难过,因为它在实际浏览器中运行良好,但在测试中却没有:如果组件使用useParams钩子,则钩子会在测试中引发错误:

错误:未捕获 [类型错误:无法解构accountId“未定义”或“空”的属性。]

我正在使用 React 功能组件、React 测试库和 React-Router:

// 成分:

const Overview: FC = () => {
  const location = useLocation();
  console.log(location) // see below
  const { accountId } = useParams();
  console.log(accountId) // see below

  ... rest
}
Run Code Online (Sandbox Code Playgroud)

控制台日志似乎已正确找到参数:

console.log src/screens/Overview/index.tsx:66 accountId: nodata

console.log src/screens/Overview/index.tsx:64 location: { pathname: '/mix/overview/nodata', search: '', hash: '', state: undefined, key: 'bn6zvv' }

// 使用RTL 文档中推荐的包装器测试设置


function renderWithProviders(
  ui,
  {
    route = '/',
    params = routes.root, 
    history …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router react-router-dom react-testing-library

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

为什么我的反应测试在 CI 管道中由于“未包装在 act() 中”而失败,而在本地工作正常?

我有一个测试套件,其中包含 37 个测试,正在测试我的一个观点。在本地,所有测试都通过,没有任何问题,但是当我推送代码时,测试套件在我们的管道中失败(我们正在使用 GitLab)。

CI 中日志的错误输出非常长(数千行,甚至超过了 GitLab 设定的限制)。该错误由许多“未包含在 act() 中”和“不支持对 act() 的嵌套调用”警告组成(Moslty 由useTranslation()I18Next 和TooltipMaterial-UI 等组件触发)。

我的猜测是,来自 API 的异步数据(使用 msw 模拟)会在调用完成后触发状态更新act(),但我不确定如何证明这一点,甚至不知道哪些测试实际上失败了。

有没有人经历过类似的事情,或者知道是怎么回事?

失败测试的示例:

it.each([
    [Status.DRAFT, [PAGE_1, PAGE_11, PAGE_2, PAGE_22, PAGE_3]],
    [Status.PUBLISHED, [PAGE_1, PAGE_12, PAGE_2, PAGE_21, PAGE_22, PAGE_221]],
  ])('should be possible to filter nodes by status %s', async (status, expectedVisiblePages) => {
    renderComponent();
    await waitFor(() => {
      expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
    });
    userEvent.click(screen.getByLabelText('components.FilterMenu.MenuLabel'));
    const overlay = await screen.findByRole('presentation');
    await waitFor(() => expect(within(overlay).queryByRole('progressbar')).not.toBeInTheDocument());
    userEvent.click(within(overlay).getByText(`SiteStatus.${status}`));
    userEvent.keyboard('{Esc}');
    
    const items = await screen.findAllByRole('link'); …
Run Code Online (Sandbox Code Playgroud)

testing reactjs gitlab-ci jestjs react-testing-library

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

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万
查看次数