James
James

Reputation: 281

Jest Unit Test - Mocking component with props

I am trying to make a Jest Mock for NextSeo where I can run assertions on the props passed to Meta.

I have a basic working example below but I am unsure of how to include props in my Mock to run assertions on.

Meta Component

const Meta = (props: Props) => {
  return (
    <NextSeo
      title={props.title == 'Homepage' ? appMeta.title : props.title}
      description={
        props.title == 'Homepage' ? appMeta.description : props.description
      }
    />
  );
};

export default Meta;

Meta Unit Test

jest.mock('next-seo', () => ({
  NextSeo: '<div></div>', // I am trying to add props here
}));

describe('<ContactUs/>', () => {
  it('can render with default props', () => {
    const ContactUsWrapper = shallow(
      <Meta title="title" description="description" />
    );

    expect(NextSeo).toEqual('<div></div>');
  });
});

What I am trying to achieve:

Mock:

jest.mock('next-seo', () => ({
   NextSeo: '<div>{props.title} {props.desctription}</div>',
}));

Spec:

expect(NextSeo).toEqual('<div>title description</div>');

Upvotes: 2

Views: 9389

Answers (1)

Lin Du
Lin Du

Reputation: 102617

You can mock NextSeo component a functional component. E.g.

index.tsx:

import React from 'react';
import { NextSeo } from './next-seo';

type Props = any;
const Meta = (props: Props) => {
  const appMeta = { title: '', description: '' };
  return (
    <NextSeo
      title={props.title === 'Homepage' ? appMeta.title : props.title}
      description={props.title === 'Homepage' ? appMeta.description : props.description}
    />
  );
};

export default Meta;

next-seo.tsx:

import React from 'react';
export const NextSeo = ({ title, description }) => <span></span>;

index.test.tsx:

import Meta from './';
import React from 'react';
import { mount } from 'enzyme';

jest.mock('./next-seo', () => ({
  NextSeo: (props) => (
    <div>
      {props.title} {props.description}
    </div>
  ),
}));

describe('<ContactUs/>', () => {
  it('can render with default props', () => {
    const ContactUsWrapper = mount(<Meta title="title" description="description" />);
    expect(ContactUsWrapper).toMatchSnapshot();
  });
});

test results:

 PASS  stackoverflow/60759940/index.test.tsx (7.958s)
  <ContactUs/>
    ✓ can render with default props (37ms)

 › 1 snapshot updated.
Snapshot Summary
 › 1 snapshot updated from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 updated, 1 total
Time:        9.08s

index.test.tsx.snap:

// Jest Snapshot v1

exports[`<ContactUs/> can render with default props 1`] = `
<Meta
  description="description"
  title="title"
>
  <NextSeo
    description="description"
    title="title"
  >
    <div>
      title

      description
    </div>
  </NextSeo>
</Meta>
`;

Upvotes: 2

Related Questions