React 测试假 XMLHttpRequest [英] React testing Fake XMLHttpRequest
问题描述
我正在为某人的应用程序编写一些测试代码.我是专门为 React 编写测试的新手.
I am writing some test code for someone's application. I am new to writing tests specifically for React.
在组件内部的方法之一中,一个新的 XMLHttpRequest
对象被实例化,然后像这样使用:
In one of the methods inside the component, a new XMLHttpRequest
object is instantiated and then used like so:
var myModal = React.createClass({
postRequest: function(data) {
var json = JSON.stringify(data)
var request = new XMLHttpRequest()
request.open('POST', '/my/endpoint', true)
request.setRequestHeader('Content-Type', 'application/json')
request.send(json)
}
//...
}
我正在使用 Sinon,他们的文档说有一个 Fake XMLHttpRequest 可用于测试 AJAX 请求.我试图了解如何使用 Sinon 来覆盖这个 new
ly 实例化的对象,以便测试使用它来进行 api 调用.
I am using Sinon, and their documentation says there is a Fake XMLHttpRequest which can be used for testing AJAX requests. I am trying to understand how exactly to override this new
ly instantiated object with the Sinon one, so that the tests uses it to make api calls.
如果我尝试将伪造值分配给 request
变量:
If I try and assign the fake to the request
variable:
before(function () {
request = sinon.useFakeXMLHttpRequest();
requests = [];
request.onCreate = function (req) { requests.push(req); };
});
当它到达组件的new XMLHttpRequest()
行时,测试仍然失败.我应该像这里那样创建和导入存根对象吗?https://github.com/danvk/mocha-react/blob/jsx-stubs/BigComplicatedComponent.js 或者我错误地试图覆盖它.
the test still falls over when it reaches the component's new XMLHttpRequest()
line. Should I just be creating and importing a stub object instead like here? https://github.com/danvk/mocha-react/blob/jsx-stubs/BigComplicatedComponent.js Or am I incorrectly trying to override it.
推荐答案
终于搞定了.将此添加到顶部.我想它应该可以覆盖任何类.
Finally got this working. Added this to the top. I'd imagine it should work with overriding any class.
var FakeXMLHTTPRequests = require('fakexmlhttprequest')
var requests = []
XMLHttpRequest = function() {
var r = new FakeXMLHTTPRequests(arguments)
requests.push(r)
return r
}
感谢这篇文章帮助我思考这个问题.http://www.asbjorenge.com/wwc/testing_react_components.html
Thanks to this article for helping me to think this through. http://www.asbjornenge.com/wwc/testing_react_components.html
如果使用 XMLHttpRequest 也可以这样做:正确使用 sinon 的伪造的 XMLHttpRequest
Can also so this for if using XMLHttpRequest: correct usage of sinon's fake XMLHttpRequest
这篇关于React 测试假 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!