ava 类似jest snapshot 功能试用
ava也提供了类似jest 的snapshot 测试,可以用来方便的测试web 组件,以下是一个简单的试用,
同时包含了自己碰到问题,以及解决方法,以及一些参考链接
使用typescript 以及tsx,测试react 组件
环境准备
- 项目结构
├── package.json
├── src
│ ├── app.ts
│ ├── hello-component.tsx
│ └── userlogin.tsx
├── tests
│ ├── app.js
│ ├── hello-component.js
│ └── userlogin.js
├── tsconfig.json
└── yarn.lock
- 代码说明
src 为typescript 代码,tests 为集成ava 测试
package.json 包含ava 的一些配置,项目依赖,以及npm script
{
"name": "@rongfengliang/ava-test-learning",
"version": "1.0.1",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"@babel/polyfill": "^7.6.0",
"@babel/preset-react": "^7.6.3",
"@babel/register": "^7.6.2",
"@types/react": "^16.9.11",
"ava": "^2.4.0",
"react": "^16.11.0",
"react-test-renderer": "^16.11.0",
"typescript": "^3.6.4",
"zen-observable": "^0.8.14"
},
"ava": {
"require": [
"@babel/register",
"@babel/polyfill"
]
},
"scripts": {
"test:live": "ava -v -w",
"test": "ava -v",
"build:live": "tsc --watch"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
}
}
tsconfig.json 文件定义
{
"compilerOptions": {
"target": "es5",
"module": "umd",
"declaration": true,
"outDir": "libs",
"rootDir": "src",
"jsx": "react",
"removeComments": false,
"strict": true,
"moduleResolution": "node"
}
}
src/app.js 可选 ,一个简单的module
// define user entity
let user = {
/** user name */
name:"dalong",
/** user age */
age:33
}
// for export default
export default {
user
}
export {
user
}
src/hello-component.tsx 一个测试组件
import React = require("react");
const HelloWorld = () => <h1>Hello World
export default HelloWorld;
src/userlogin.tsx 另外一个测试组件
import React = require("react");
/**
* loginForm component
*/
const LoginForm = ()=>
<div>
<h1>userename </h1>
<input placeholder="please input your name" />
<h1>pasword</h1>
</div>
export default LoginForm;
tests/hello-component.js snapshot 测试,userlogin.js 类似
babel 配置,为了简单使用6的格式,进行react 的处理,vue 也类似的
{
"presets": ["@babel/preset-react"]
}
启动&&测试
- 启动实时编译
yarn build:live
- 启动测试
yarn test:live
- 效果
修改组件,查看snapshot
src/hello-component.tsx
import React = require("react");
const HelloWorld = () => <h1>dalong World
export default HelloWorld;
几个问题
- 新版本的变动
新版本为了支持babel 7 ava 做了好多修改
比如package.json 中关于ava 的配置以及依赖的preset
"ava": {
"require": [
"@babel/register",
"@babel/polyfill"
]
}
- regeneratorRuntime is not defined
添加@babel/polyfill
说明
以上是一个简单的试用,还是得多看看github issue
参考资料
https://github.com/avajs/ava/issues/1640
https://github.com/avajs/ava/issues/1968
https://github.com/avajs/ava/issues/685
https://github.com/rongfengliang/ava-test-learning