I am building a simple React app and trying to test some functions that perform some logic within the components. I have cypress tests but I'm now trying to use jest.
This particular function needs to return the most frequent string. The function currently works, and is like so...
favourite(item) {
return item.sort((a,b) =>
item.filter(v => v===a).length
- item.filter(v => v===b).length
).pop();
}
and my test (not currently working) looks like this...
import React from "react";
import { create } from "react-test-renderer";
import ShoppingCart from "../components/ShoppingCart";
describe("most frequent shopping item", () => {
test("returns the most frequent string in an array", () => {
const component = create(<ShoppingCart />);
const instance = component.getInstance();
items = ["eggs", "jam", "jam", "milk", "bread" ]
expect(instance.favourite(items)).toBe("jam");
});
});
My test is reading the props of the component but gets:
cannot read property 'length' of undefined
I call .length on the array in the component.
Any suggestions on how I can test simple functions in components would be much appreciated!