首页 > 解决方案 > 是否可以将酶测试与 Next js (SSR) 一起使用?

问题描述

这是我第一个使用 SSR 的 Nextjs 项目。

为 Reactjs UI 测试集成酶时。它无法运行,因为“React”引用了一个 UMD 全局,但当前文件是一个模块。考虑添加一个导入。

但是当我使用普通的 Reactjs 组件(功能或类)时它是有效的。任何人请提出建议。

沙盒链接 - https://codesandbox.io/s/currying-moon-gdk09

来自 GitHub 的完整代码 - https://github.com/Rizz13/nextJs-with-Enzyme

运行测试使用“npm test”

页面/索引.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
    }
  }
}

_测试_/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);
  });

});

当我使用上面的代码测试由于以下错误而无法运行时。

在此处输入图像描述

标签: reactjsunit-testingnext.jsenzymereact-tsx

解决方案


测试/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);
  });

});

您必须在测试组件中传递道具并使用

import * as React from 'react'

pages/Index.tsx中用于渲染反应组件


推荐阅读