ava 相似jest snapshot 功能試用

ava也提供了相似jest 的snapshot 測試,能夠用來方便的測試web 組件,如下是一個簡單的試用,
同時包含了本身碰到問題,以及解決方法,以及一些參考連接vue

使用typescript 以及tsx,測試react 組件node

環境準備

  • 項目結構
 
├── 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 文件定義react

{
  "compilerOptions": {
    "target": "es5", 
    "module": "umd", 
    "declaration": true, 
    "outDir": "libs", 
    "rootDir": "src",
    "jsx": "react",
    "removeComments": false,
    "strict": true,
    "moduleResolution": "node"
  }
} 

src/app.js 可選 ,一個簡單的modulegit

// 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 一個測試組件github

import React = require("react");
const HelloWorld = () => <h1>Hello World...!</h1>;
export default HelloWorld;
 

src/userlogin.tsx 另一個測試組件web

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 也相似的typescript

 
{
    "presets": ["@babel/preset-react"]
}

啓動&&測試

  • 啓動實時編譯
yarn build:live
  • 啓動測試
yarn test:live
  • 效果

 

 

修改組件,查看snapshot
src/hello-component.tsxnpm

 
import React = require("react");
const HelloWorld = () => <h1>dalong World...!</h1>;
export default HelloWorld;
 

 

 

幾個問題

  • 新版本的變更
    新版本爲了支持babel 7 ava 作了好多修改
    好比package.json 中關於ava 的配置以及依賴的preset
 
 "ava": {
    "require": [
      "@babel/register",
      "@babel/polyfill"
    ]
  }
  • regeneratorRuntime is not defined
    添加@babel/polyfill

說明

以上是一個簡單的試用,仍是得多看看github issuejson

參考資料

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-learningbabel

相關文章
相關標籤/搜索