Is it Possible to use Enzyme testing with Next js (SSR)?

1.5k views Asked by At

It's My first Nextjs project with SSR.

When Integrating Enzyme For Reactjs UI Testing. it could not run due to "React' refers to a UMD global, but the current file is a module. Consider adding an import instead."

but it's works when i am using normal Reactjs Component(Functional or Class). Anyone Please give suggestions.

SandBox Link - https://codesandbox.io/s/currying-moon-gdk09

Full code From GitHub - https://github.com/Rizz13/nextJs-with-Enzyme

to run testing Use "npm test"

pages/Index.tsx

import Head from 'next/head'
import Link from 'next/link'
import { GetStaticProps } from 'next'

export default function Home({
  allPostsData
}: {
  allPostsData: {
    title: string
    id: string
  }[]
}) {
  return (
    <>
      <Head>
        <title>Sample Page</title>
      </Head>
      
      <section className="icon-stars">
        <p>[Your Self Introduction]</p>
        <p>
          (This is a sample website - you’ll be building a site like...)
        </p>
      </section>
      <section>
        <h2>Blog</h2>
        <ul>
          {allPostsData.map(({ id, title }) => (
            <li key={id}>
              <Link href="#">
                <a>{title}</a>
              </Link>
              <br />
            </li>
          ))}
        </ul>
      </section>
    </>
  )
}

export const getStaticProps: GetStaticProps = async () => {
  const allPostsData = [{id: 0, title:"Sample1"}, {id: 1, title:"Sample2"}]
  return {
    props: {
      allPostsData
    }
  }
}

_tests_/Index.tsx

import * as React from 'react'
import { expect as expect1 } from 'chai';

import IndexPage from '../pages/index'

import {/*mount,*/ shallow} from 'enzyme' 

const setUp1 = (data) => {
  return shallow(<IndexPage {...data} />);
}
let wrapper;

describe('props Check', () => {

  beforeEach(() => {
      wrapper = setUp1({});
  });

  it('should render an `.icon-stars`', () => {
    expect1(wrapper.find('.icon-stars')).to.have.length(1);
  });

});

When I using the Above Code Testing could not run due to below Error.

enter image description here

1

There are 1 answers

0
fullstack js On BEST ANSWER

tests/Index.tsx

import * as React from 'react'
import { expect as expect1 } from 'chai';

import IndexPage from '../pages/index'

import {/*mount,*/ shallow} from 'enzyme' 

const setUp1 = (data) => {
  return shallow(<IndexPage {...data} />);
}
let wrapper;

describe('props Check', () => {

  beforeEach(() => {
      wrapper = setUp1(allPostsData={[]});
  });

  it('should render an `.icon-stars`', () => {
    expect1(wrapper.find('.icon-stars')).to.have.length(1);
  });

});

You have to pass props inside the testing component & use

import * as React from 'react'

In pages/Index.tsx for rendering react components