8
votes

I have a basic function:

components/FirstComponent:

sayMyName = (fruit) => {
    alert("Hello, I'm " + fruit);
    return fruit;
}

When I try to test it with Jest inside FirstComponent.test.js:

import FirstComponent from '../components/FirstComponent';

describe('<FirstComponent />', () => {
    it('tests the only function', () => {
        FirstComponent.sayMyName = jest.fn();
        const value = FirstComponent.sayMyName('orange');
        expect(value).toBe('orange');
    });
});

Test says: Comparing two different types of values. Expected string but received undefined.

Apparently I'm not importing the function to test the right way?

I was not smart enough to understand the Jest documents how to test functions from components..

Is there some simple way to import function from component and test it?

Edit: This works now using the 'react-test-renderer'

import FirstComponent from '../components/FirstComponent';
import renderer from 'react-test-renderer';

describe('<FirstComponent /> functions', () => {
        it('test the only function', () => {
            const wrapper = renderer.create(<FirstComponent />);
            const inst = wrapper.getInstance();
            expect(inst.sayMyName('orange')).toMatchSnapshot();
        });
})
1

1 Answers

4
votes

You have stubbed the function with one that does not return anything. FirstComponent.sayMyName = jest.fn();

To test the function, typically you can just do

// if static etc
import { sayMyName } from '../foo/bar';

describe('bar', () => {
  it('should do what I like', () => {
    expect(sayMyName('orange')).toMatchSnapshot();
  });
})

This will store the output ("orange") and assert that every time you run this test, it should return orange. If your function stops doing that or returns something else, snapshot will differ and test will fail.

the direct comparison .toBe('orange') will still be possible but the really useful thing about jest is snapshot testing so you don't need to duplicate logic and serialise/deep compare structures or jsx.

if it's a component method, you need to render it first, getInstance() and then call it.