用於 Karma 的 Chai 快照測試外掛
快照序列化
快照格式
快照可以儲存為不同的格式。目前支援兩種格式:md
和 indented-md
。
Markdown 格式
當您為斷言外掛中的程式碼區塊指定語言時,建議使用此格式。使用此格式,程式碼編輯器將自動突出顯示程式碼區塊的語法。
# `src/html.js`
## `Sub Suite`
#### `HTML Snapshot`
```html
<div>
<span />
</div>
```
縮排 Markdown 格式
# `src/html.js`
## `Sub Suite`
#### `HTML Snapshot`
<div>
<span />
</div>
快照檔案路徑
快照檔案路徑從根測試案例的名稱中提取,並與受測試的檔案一起儲存在 __snapshots__
目錄中。
可以透過在快照設定中提供自訂 pathResolver
來變更快照檔案路徑。
使用範例
$ npm install karma karma-webpack karma-sourcemap-loader karma-snapshot karma-mocha \
karma-mocha-snapshot karma-mocha-reporter karma-chrome-launcher mocha \
chai chai-karma-snapshot webpack --save-dev
Karma 設定
// karma.conf.js
const webpack = require("webpack");
module.exports = function (config) {
config.set({
browsers: ["ChromeHeadless"],
frameworks: ["mocha", "snapshot", "mocha-snapshot"],
reporters: ["mocha"],
preprocessors: {
"**/__snapshots__/**/*.md": ["snapshot"],
"__tests__/index.js": ["webpack", "sourcemap"]
},
files: [
"**/__snapshots__/**/*.md",
"__tests__/index.js"
],
colors: true,
autoWatch: true,
webpack: {
devtool: "inline-source-map",
performance: {
hints: false
},
},
webpackMiddleware: {
stats: "errors-only",
noInfo: true
},
snapshot: {
update: !!process.env.UPDATE,
prune: !!process.env.PRUNE,
},
mochaReporter: {
showDiff: true,
},
client: {
mocha: {
reporter: "html",
ui: "bdd",
}
},
});
};
原始檔案
// src/index.js
export function test() {
return "Snapshot Test";
}
測試檔案
// __tests__/index.js
import { use, expect, assert } from "chai";
import { matchSnapshot } from "chai-karma-snapshot";
import { test } from "../src/index.js";
use(matchSnapshot);
describe("src/index.js", () => {
it("check snapshot", () => {
// 'expect' syntax:
expect(test()).to.matchSnapshot();
// 'assert' syntax:
assert.matchSnapshot(test());
});
});
執行測試
$ karma start
更新快照
$ UPDATE=1 karma start --single-run
修剪快照
$ PRUNE=1 karma start --single-run
設定
function resolve(basePath, suiteName) {
return path.join(basePath, "__snapshots__", suiteName);
}
config.set({
...
snapshot: {
update: true, // Run snapshot tests in UPDATE mode (default: false)
prune: false, // Prune snapshots for removed tests (default: true)
format: "indented-md", // Snapshot format (default: md)
checkSourceFile: true, // Checks existince of the source file associated with tests (default: false)
pathResolver: resolve, // Custom path resolver
}
});
自訂快照格式
快照設定選項 format
也適用於自訂序列化格式。自訂快照序列化器應具有以下介面
interface SnapshotSerializer {
serialize: (name: string, suite: SnapshotSuite) => string,
deserialize: (content: string) => { name: string, suite: SnapshotSuite },
}