ESMおよびプラグインを使用したChaiの使用
このガイドでは、ECMAScriptモジュール(ESM)とプラグインを併用してChaiを使用する方法の概要を説明します。また、chai-http
プラグインを使用した例も挙げます。
Chaiのインポート
ESMでChaiを使用するには、テストファイルでimport
ステートメントを使用して、Chaiをインポートできます。expect
インターフェースをインポートする方法を次に示します。
import { expect } from 'chai';
プラグインの使用
ChaiプラグインはChaiの機能を拡張できます。プラグインを使用するには、まずインストールする必要があります。次に、use
メソッドを使用してプラグインをロードします。例として、chai-http
プラグインを使用する方法を次に示します。
import chai from 'chai';
import { request }, chaiHttp from 'chai-http';
chai.use(chaiHttp);
// Now you can use `chai-http` using the `request` function.
chai-http の例
HTTP GET リクエストのテストに chai-http
を使用した例を示します
import chai, { expect } from 'chai';
import { request }, chaiHttp from 'chai-http';
chai.use(chaiHttp);
describe('GET /user', () => {
it('should return the user', done => {
request('http://example.com')
.get('/user')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.an('object');
done();
});
});
});