【问题标题】:Testing functions in jest开玩笑地测试功能
【发布时间】:2018-09-25 06:29:41
【问题描述】:

我需要一些关于如何和什么方面测试功能的建议

说我有一些状态。

state = {
  categories: [this is full of objects],
  products: [this is also full of objects]
}

那么我有这个功能:

  filterProducts = () => {
    return this.state.products.filter((product => (
      product.categories.some((cat) => (
         cat.title == this.state.chosenCategory
      ))
    )))
  }

此函数通过计算产品是否属于所选类别来过滤产品数组。

你会如何测试这个?

我试过了

 let productsStub = [
    {id: 1, title: 'wine01', showDescription: false},
    {id: 2, title: 'wine02', showDescription: false},
    {id: 3, title: 'wine03', showDescription: false}
  ]
  wrapper = shallow(<Menu
    categories={categoriesStub}
    products={productsStub}
    />);


  it('should filter products when searched for', () => {
    const input = wrapper.find('input');
    input.simulate('change', {
      target: { value: '01' }
    });
    expect(productsStub.length).toEqual(1);
  });

这个测试(我认为)在说什么,当我搜索 01 时,我希望产品状态(以及状态的存根)过滤并仅返回 1 个结果。但是测试失败并显示预期:1 收到:3 即过滤不起作用。

我知道我也可以做wrapper.instance.filterProducts(),但同样,我对开玩笑的功能测试不太满意。

有什么建议吗?和某人聊天会很棒

谢谢

【问题讨论】:

  • 如果您能提供codesandbox.io或其他工具中的代码,那就太好了,我们可以谈谈。
  • @ChasingUnicorn 你还想要什么代码对不起?它只是一个过滤状态数组的函数,我想知道如何测试它..?

标签: javascript reactjs testing jestjs


【解决方案1】:

我复制了您的问题陈述,但不确定您如何维护状态模型(道具/状态)。但这可能会有所帮助。 :)

在此处查看工作示例:https://codesandbox.io/s/6zw0krx15k

import React from "react";

export default class Hello extends React.Component {
  state = {
    categories: [{ id: 1 }],
    products: this.props.products,
    selectedCat: 1,
    filteredProducts: []
  };

  filterProducts = value => {
    let filteredVal = this.props.products.filter(
      product => product.id === parseInt(value)
    );

    this.setState({
      filteredProducts: filteredVal
    });
  };

  setValue = e => {
    this.setState({
      selectedCat: e.target.value
    });
    this.filterProducts(e.target.value);
  };

  render() {
    return (
      <div>
        Filter
        <input value={this.state.selectedCat} onChange={this.setValue} />
      </div>
    );
  }
}


import { shallow } from "enzyme";
import Filter from "./Filter";
import React from "react";


let productsStub = [
  { id: 1, title: "wine01", showDescription: false },
  { id: 2, title: "wine02", showDescription: false },
  { id: 3, title: "wine03", showDescription: false }
];
let wrapper = shallow(<Filter products={productsStub} />);

it("should filter products when searched for", () => {
  const input = wrapper.find("input");
  input.simulate("change", {
    target: { value: "1" }
  });
  expect(wrapper.state().filteredProducts.length).toEqual(1);
});

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2020-12-15
    • 2020-07-04
    • 1970-01-01
    • 2018-08-30
    • 2019-05-08
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多