reactjs - 是否可以将酶测试与 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);
});
});
当我使用上面的代码测试由于以下错误而无法运行时。
解决方案
测试/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中用于渲染反应组件
推荐阅读
- javascript - 如何在没有 JavaScript 的情况下分离键盘选项卡旋转组?
- javascript - 如何在数据库基本初始化后让 MongoDB 消化一个 javascript 文件?
- if-statement - 如何将tableau中的ifnull语句转换为powerbi dax?
- python - python请求响应中的“原始”属性是什么意思?
- javascript - 无法理解 React setState 签名“setState(updater[, callback])”
- angular - 更新时未选择 Angular 8 Material 特定的垫子选项
- html - 全宽元素内的内容应容器化
- ios - 当键盘出现在 SwiftUI 中时向上移动 TextField
- zabbix - Zabbix - 代理活动检查的自定义间隔
- powerbi - 在 Power BI 中正确显示持续时间和格式