更多npm常用模塊使用請訪問:npm常用模塊匯總
chai這是一款用於節點和瀏覽器的BDD / TDD斷言庫,可以與任何javascript測試框架完美地配對。
安裝
一鍵安裝不多解釋
npm install --save-dev chai
使用
瀏覽器
您也可以在瀏覽器中使用它。通過npm安裝並使用chai.js下載中找到的文件。例如:
<script src="./node_modules/chai/chai.js"></script>
導入庫中的代碼,然后挑選的款式之一,你想使用-要么assert
,expect
或should
:
var chai = require('chai');
var assert = chai.assert; // 使用斷言樣式
var expect = chai.expect; // 使用Expect樣式
var should = chai.should(); // 使用Should樣式
本機模塊用法(在全球注冊chai測試樣式)
require('chai/register-assert'); // 使用斷言樣式
require('chai/register-expect'); // 使用Expect樣式
require('chai/register-should'); // 使用Should樣式
本地模塊的用法(作為局部變量)
const { assert } = require('chai'); // 使用斷言樣式
const { expect } = require('chai'); //使用Expect樣式
const { should } = require('chai'); // 使用Should樣式
should(); // 修改Object.prototype
const { expect, use } = require('chai'); // 創建局部變量`expect`和`use`; 對於插件使用很有用
本機模塊用法(全局注冊chai測試樣式)
import 'chai/register-assert'; // Using Assert style
import 'chai/register-expect'; // Using Expect style
import 'chai/register-should'; // Using Should style
本機模塊用法(僅本地導入)
import { assert } from 'chai'; // 使用斷言樣式
import { expect } from 'chai'; // 使用expect風格
import { should } from 'chai'; // 使用Should樣式
should(); // 修改Object.prototype
與摩卡搭配使用
mocha spec.js -r chai/register-assert # 使用斷言樣式
mocha spec.js -r chai/register-expect # 使用Expect樣式
mocha spec.js -r chai/register-should # 使用Should樣式
外掛程式
Chai提供了健壯的插件架構,用於擴展Chai的斷言和接口。
- 需要插件嗎?查看官方插件列表。
- 要構建插件嗎?閱讀插件9api文檔](http://chaijs.com/guide/plugins/)。
- 有一個插件並想要列出嗎?只需將以下關鍵字添加到package.json中:
chai-plugin
browser
如果您的插件可以在瀏覽器以及Node.js中運行browser-only
如果您的插件不適用於Node.js