dimanche 15 avril 2018

Testing functions in jest

I need some advice on testing functions in terms of how and what

say I have some state.

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

then I have this function:

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

this function filters the products array by working out if the products are part of the selected category.

how would you test this?

I've tried this

 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);
  });

what this test (I think) is saying, when I search for 01, I expect the product state (well the stub of the state) to filter and return only 1 result. however the test fails and says expected: 1 received: 3 i.e. the filtering isn't working.

I know I could also do wrapper.instance.filterProducts() but again, I'm not very comfortable on function testing in jest.

any advice? would be great to chat it through with someone

thanks

Aucun commentaire:

Enregistrer un commentaire