luis
luis

Reputation: 202

Testing jest unit test and always get undefined

let's I have the following functional component in React

const TestComponent = ({ name, ...props }) => {


  return (
    <div>
      {name}
    </div>
  );
};

TestComponent.propTypes = {
  name: T.object,
  classes: T.object,
};

export default TestComponent

on my test i have this

describe('Test component ', () => {
    it("name should match", () => {
        const obj ={
            name: "Test",
        };
        const wrapper = shallow(<TestComponent name={obj}/>);
        expect(wrapper.name).toEqual({
            name: "Test",
        })
    });
});

when i run npm test i keep getting wrapper is undefined

    Expected: {"name": "Test"}
    Received: undefined

      35 |         };
      36 |         const wrapper = shallow(<TestComponent name={obj}/>);
    > 37 |         expect(wrapper.name).toEqual(obj)
         |                                 ^
      38 |     });
      39 | });
      40 | 

I'm trying to match both object but I'm not sure why i keep getting undefined despite i already sent the info

Upvotes: 1

Views: 4175

Answers (1)

Lin Du
Lin Du

Reputation: 102207

You should use .props() => Object API of enzyme. E.g.

index.tsx:

import React from 'react';

const TestComponent = ({ name, ...props }) => {
  return <div>{name}</div>;
};

export default TestComponent;

index.test.tsx:

import TestComponent from './';
import React from 'react';
import { shallow } from 'enzyme';

describe('61087595', () => {
  it('should pass', () => {
    const obj = {
      name: 'Test',
    };
    const wrapper = shallow(<TestComponent name={obj} />);
    expect(wrapper.props().children).toEqual({ name: 'Test' });
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/61087595/index.test.tsx (7.805s)
  61087595
    ✓ should pass (6ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.868s, estimated 10s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61087595

Upvotes: 1

Related Questions