【问题标题】:TypeError: Cannot read property 'change' of undefinedTypeError:无法读取未定义的属性“更改”
【发布时间】:2019-02-25 11:58:21
【问题描述】:

为什么下面的代码会出现这个错误?我已经从 'react-testing-library' 导入了 'Simulate' 但错误指出 'Simulate' 是 'undefined'

import React from 'react';
import { render, Simulate } from 'react-testing-library';
import CommentFeed from './CommentFeed';

const createProps = props => ({
header: 'Comment Feed',
comments: [
   {
      author: 'Ian Wilson',
      text: 'A boats a boat but a mystery box could be anything.',
   },
   {
     author: 'Max Powers Jr',
     text: 'Krypton sucks.',
   },
  ],
  createComment: jest.fn(),
  ...props,
})

describe('CommentFeed', () => {
  const props = { header : 'Comment Feed', comments : []};

  /* ... */

  it('allows the user to add a comment', () => {
    // Arrange
    const newComment = { author: 'Socrates', text: 'Why?' };
    let props = createProps();
    const { container, getByLabelText } = render(<CommentFeed {...props} />);

    const authorNode = getByLabelText('Author');
    const textNode = getByLabelText('Comment');
    const formNode = container.querySelector('form');

   // Act
    authorNode.value = newComment.author;
    textNode.value = newComment.text;

    Simulate.change(authorNode); // Where the error occurs
    Simulate.change(textNode);

    Simulate.submit(formNode);

    // Assert
    expect(props.createComment).toHaveBeenCalledTimes(1);
    expect(props.createComment).toHaveBeenCalledWith(newComment);
  });
});

我正在搜索这个问题,但找不到任何有关“模拟”行为的信息

【问题讨论】:

  • 欢迎来到 SO!我在 react-testing-library 的 GitHub 页面上找不到对 Simulate 的任何引用。你是从一个特定的例子开始工作的吗?
  • 是的。来自这个:dev.to/iwilsonq/…
  • 什么是“这个错误”,它出现在所有代码的什么地方?

标签: javascript reactjs react-testing-library


【解决方案1】:

Simulate 已从 react-testing-library 中删除。今天需要用到的是fireEvent

你可以这样使用:

import { fireEvent } from 'react-testing-library'

// Then in your test

fireEvent.change(authorNode, { target: { value: newComment.author } })

您可以在official docs 中阅读有关fireEvent 的更多信息。

【讨论】:

    【解决方案2】:

    尝试过 var test = new Simulate(); ?

    然后做 test.etc....

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2019-08-19
      相关资源
      最近更新 更多