Jest basics: Testing function from component

29,922

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.

Share:
29,922

Related videos on Youtube

Jack M.
Author by

Jack M.

Updated on August 04, 2020

Comments

  • Jack M.
    Jack M. over 3 years

    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();
            });
    })
    
  • Jack M.
    Jack M. over 6 years
    Hmm. I keep getting: TypeError: (0 , _FirstComponent.sayMyName) is not a function
  • Jack M.
    Jack M. over 6 years
    Oh I tried it with enzyme. Now works with 'react-test-renderer'
  • Dimitar Christoff
    Dimitar Christoff over 6 years
    you did say jest - not enzyme. typically though: const tree = renderer.create(<Foo />); tree.getInstance().method()