chai-fetch 
Chai 匹配器,使匹配 fetch 回應更清晰且容易
fetch('http://example.com').then((response) => response.text()).then((text) => expect(text).to.equal('hi there'))
幾乎是對 fetch 回應主體進行斷言最簡單的方式,但這是一個非常可怕的混亂。這個函式庫消除了這種痛苦,讓生活更輕鬆。
開始使用
使用以下方式安裝 chai-fetch
npm install --save-dev chai-fetch
Chai-fetch 是一個 commonjs 模組,應該可以在 node 中直接使用,或是使用像 browserify 和 webpack 等打包工具。
Chai-fetch 是用 TypeScript 編寫的,因此可以完美地與 JS 一起使用,但如果您也使用 TypeScript,您也會獲得開箱即用的型別定義。
使用此函式庫的範例測試(使用 http-server-mock 模擬 HTTP 回應)如下所示
const chai = require('chai');
const chaiFetch = require('chai-fetch');
chai.use(chaiFetch);
const { expect } = chai;
describe('Chai-fetch', () => {
beforeEach(() => mockServer.start(8080));
afterEach(() => mockServer.stop());
describe('.responseText', () => {
it('should match responses with matching bodies', () => {
mockServer.get('/match').thenReply(200, 'matching body')
.then(() =>
expect(fetch('https://#:8080/match')).to.have.responseText('matching body')
);
});
});
});
提示
-
請記住,此處的斷言都是非同步的,因此您需要
return
或.then
或await
它們,以確保您的測試框架等待結果並捕獲失敗。 -
請查看 http-server-mock 來模擬您的伺服器回應。
-
如果您正在編寫類似這樣的 HTTP 測試,並且您正在使用 Babel、TypeScript 或僅僅是一些非常現代的 JS 引擎,您可以使用 async/await 使它們更具可讀性
it('should match responses with matching bodies', async () => { await mockServer.get('/match').thenReply(200, 'matching body'); await expect(fetch('https://#:8080/match')).to.have.responseText('matching body'); });
API
.responseText(expectedText)
例如: expect(fetch('http://example.com')).to.have.responseText('hi there')
如果被測試的物件是 fetch 回應,或 fetch 回應的 promise,則此斷言會確認主體的完整文字與給定的文字相等。
您也可以傳遞正規表示式: .responseText(/match a substring/)
。
這並不測試狀態碼(就像 fetch 本身不會測試一樣),但是如果傳遞的回應 promise 完全被拒絕(例如,如果您有網路錯誤),則正常測試和否定測試都會失敗。
.status(expectedStatus)
例如: expect(fetch('http://example.com')).to.have.status(200)
如果被測試的物件是 fetch 回應,或 fetch 回應的 promise,則此斷言會確認回應的狀態是給定的狀態。