Testing XHR with Jest
Testing XHR with Jest
我有一个简单的测试用例:
describe ('Request', function () {
it ('should perform a XHR "GET" request', function (done) {
var xhr = new XMLHttpRequest;
xhr.open('GET', 'http://google.com', true);
xhr.send();
});
});
重点是:当我在终端中执行jest
时,它似乎没有请求http://google.com
。我认为发生这种情况是因为Jest在后台使用jsdom,并且它无法从浏览器本身复制HTTP请求。
建议?
注意:出现任何错误,测试通过,但没有发出请求
我假设您不想做单元测试,而是打算创建某种集成测试,或者您想为正在调用的API编写测试。
在这两种情况下,您都必须为全局作用域提供XMLHttpRequest对象,因为它不存在于nodejs(运行测试代码的平台)中
您可以通过安装此软件包来完成此操作:https://www.npmjs.com/package/xmlhttprequest
然后在任何测试之前运行此代码:
global.XMLHttpRequest=require("XMLHttpRequest").XMLHttpRequest;
您也可以不使用jest来实现这一目的,并使用chakram或frisby,这两种都是为API测试而构建的,并且都会为您提出请求。
有很多问题:
- 在您的代码示例中,您没有创建XMLHttpRequest的实例。它应该是这样的:
var xhr = new XMLHttpRequest()
- 在测试中提出真正的请求是个坏主意。如果您的模块依赖于来自远程服务器的数据,则应该模拟XMLHttpsRequest或使用"假服务器"(例如sinon)。我强烈建议你不要在测试中提出真正的要求
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 使用Jest测试React Native应用程序
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- Architecture for CPU intensive tasks with NodeJS & Socke
- How to declare a Map containing certain properties with flow
- 设置'这'在React with Inverse Data Flow中
- Unit-testing multiple use cases with Karma & Mocha.js
- Testing XHR with Jest
- 在 React with Jest 中测试模拟表单输入
- has no method 'mountComponentIntoNode' with Jest + R