【问题标题】:Test text input with react and jest使用 react 和 jest 测试文本输入
【发布时间】:2017-05-14 19:44:57
【问题描述】:

我的一个小型测试项目中有一个简单的SearchBar 组件。 这个 SearchBar 主要由一个文本输入和一个按钮组成, 按钮单击使用输入字段中的文本执行回调。

我的Searchbar.render 方法如下所示:

  return (
    <FormGroup controlId="keywords">
      <InputGroup>
        <FormControl type="text"
                     placeholder="Keywords…"
                     value={this.state.keywords}
                     onChange={this.updateKeywords} />
        <InputGroup.Button
          onClick={() => {this.props.onSearch(this.state.keywords);}}
          ref="searchInput">
          <Button ref="searchButton">
            <Glyphicon glyph="search"/>
          </Button>
        </InputGroup.Button>
      </InputGroup>
    </FormGroup>
  );

我用玩笑为它写了一个test

it("should adjust keywords and trigger onSearch correctly", () => {
  const handleSearch = jest.fn();

  const searchBar = ReactTestUtils.renderIntoDocument(
    <Searchbar onSearch={handleSearch}/>
  );
  expect(searchBar.state.keywords).toBe("");

  const button = ReactDOM.findDOMNode(searchBar.refs.searchButton);
  const input = ReactDOM.findDOMNode(searchBar.refs.searchInput);

  ReactTestUtils.Simulate.change(input, {target: {value: "test"}});

  ReactTestUtils.Simulate.click(button);
  expect(handleSearch).toHaveBeenCalledWith("test");
});

现在这个测试中的回调可以正常工作,并且存储在callMe get 中的函数按预期调用。 SearchBar 也适用于我的应用程序,所以我认为 SearchBar 代码是正确的。但是当我使用npm test 运行我的测试时,测试失败了:

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

Expected mock function to have been called with:
  ["test"]
But it was called with:
  [""]

在 cmets Andreas Köberle 中指出了 updateKeywords 方法似乎没有被调用的问题,这应该是测试失败的原因。可悲的是,我无法弄清楚为什么在测试中没有调用此方法。

【问题讨论】:

    标签: reactjs ecmascript-6 jestjs react-bootstrap


    【解决方案1】:

    您必须自己传递事件数据,因为它不会真正触发 DOM 元素上的事件。来自文档:

    您必须提供您在您的 React 没有创建任何组件(例如 keyCode、which 等) 这些给你。

    在你的组件中加入一个 spy 函数作为回调也很常见,并在模拟事件后对其进行测试。

    const handleSearch = jest.fn();
    const searchBar = ReactTestUtils.renderIntoDocument(
        <Searchbar onSearch={handleSearch}/>
    );
    ReactTestUtils.Simulate.change(input, {target: {value: 'test'}});
    expect(handleSearch).toHaveBeenCalledWith('test')
    

    【讨论】:

    • 感谢指点!可悲的是,到目前为止它还没有奏效。我已经调整了我的Searchbar.test.jsnpm test 仍然抱怨。我已经调整了我的 master 分支,希望能够更容易地重现。
    • 很好,我不知道toHaveBeenCalledWith 方法。这更优雅,但我的测试仍然失败。我已经相应地更新了问题和主分支。
    • 我建议通过在updateKeywords 方法中添加log 来检查它是否被调用。
    • 嗯。看来你的领导是对的。 updateKeywords 函数似乎没有在测试中被调用。但它是在浏览器中调用的。我不明白这是怎么回事,但会进一步调查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2020-06-14
    • 2020-06-01
    • 2021-09-20
    • 2017-07-04
    • 2022-11-21
    相关资源
    最近更新 更多