1

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!

1 Answer 1

1

Separately define the function inside your component file (but outside the component), export it and test it, without the need for a component to be instantiated inside the test case. Of course, you can use it inside the component as well.

export const favourite = function(item){
    return item.sort((a,b) =>
    item.filter(v => v===a).length
    - item.filter(v => v===b).length
    ).pop();
}

Then in your test you can do

import { favourite } from 'path/to/file';

describe('favourite', () => {

    it('should return the item that occurs most frequently', () => {

        const items = ["eggs", "jam", "jam", "milk", "bread" ]
        expect(favourite(items)).toBe("jam");

    });

});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks very much. and in the test file what comes before favourite / what do i actually call that function on? would it be expect(this.favourite(items)).toBe etc. etc.?
No, since you import the function directly you can call it like you would any other import. I've updated my answer to give you a concrete example. Also, I completely missed that you did not assign items to a const, let or var in your original example. That can also be a reason why it doesn't work.
thanks very much. i've just exported them and tested them for now. appreciate it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.