Danny Heinrich
Danny Heinrich

Reputation: 21

testing simple functions in React

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!

Upvotes: 1

Views: 967

Answers (1)

Developenguin
Developenguin

Reputation: 176

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

    });

});

Upvotes: 1

Related Questions