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,则断言响应的状态是给定的状态。