想在 Node.js 使用 Mocha 來寫測試,但也想要用 ESM 的 import 語法,該怎麼辦呢?
現在不用 Babel 也可以做到了喔!{% fa_inline node-js fab %}
Mocha
最近想要用 Node.js 來寫個小程式方便查詢管理論文,看看之前寫 Node.js 其實也有一陣子了,雖然發覺它還是運作得很好,有點開心的啦!{% fa_inline smile %}
所以這次刻意練習以及跑一個完整一點流程,那麼 TDD 步驟第一步說先加個測試,1. Add a test 那麼就來裝一下覺得不錯用的測試工具 Mocha 吧。
$ npm install mocha --save-dev
順便從範例看看測試檔案如何寫:
var assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
ESM
可是想要用 ESM 的 import assert from 'assert' 啊,那該怎麼辦呢?
其實 Node.js 也可以用的喔,參考 ESM 的說明,只要把檔名改成 .mjs 就會以 ESM 的方式看待這個檔案,所以來把範例的測試檔改成 .mjs 結尾,並且設定好 Mocha,這樣就可以使用了,順便也改用 arrow function 表示吧。
"scripts": {
"test": "mocha ./tests/**/test*.mjs"
},
import assert from 'assert'
describe('esm.import', () => {
describe('assert', () => {
it('should return -1 when the value is not present', () => {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
最後就可以跑個最簡單測試了!
$ make test
> arxiv-pdfs@1.0.0 test /home/yumaokao/teas/arxiv-pdfs
> mocha ./tests/**/test*.mjs
esm.import
assert
✓ should return -1 when the value is not present
1 passing (5ms)
Chai
Mocha 可以使用其他的 assert 方式,之前就跟 Chai 一起搭配使用過覺得還不錯,那就繼續用 npm 來裝一下:
$ npm install chai --save-dev
其實我個人比較喜歡用 expect 的方法,用 should 會在 Object 裡面加東西啊!而 Mocha 其實可以另外設定 --require 所以來把 package.json 改一下:
"scripts": {
"test": "mocha ./tests/**/test*.mjs --require chai/register-expect"
},
嘿,這樣一來就可以用 Chai 的 expect 方式來 assert 了,把之前的 tests 改一下吧:
import assert from 'assert'
describe('esm.import', () => {
describe('chai.expect', () => {
it('should return -1 when the value is not present', () => {
expect([1, 2, 3]).to.be.a('array');
expect([1, 2, 3].indexOf(4)).to.equal(-1);
});
});
});
這樣比較有語意情境的感覺,就以這個開始繼續擴展其他的測試吧!