首页 文章

Sinon Fakeserver测试不同的组件/文件 - 没有请求?

提问于
浏览
1

我正在使用Mocha / Chai / Sinon测试一个React组件,并使用 renderedComponent.getTodos(callback) 之类的东西在不同的文件中调用AJAX请求 . 我正在传递类似于Sinon FakeServer tutorial的回调 . 但是,我收到一个奇怪的语法错误,导致不调用回调,因此 server.requests 为空 .

我知道我问了一个类似的问题here - 但是,这个问题是's different here is that I'm在一个不同的文件中调用AJAX请求,而不是同一个文件,现在之前工作的解决方案不再有效 . 我不知道为什么 . 一般来说,我的问题是: Is there something about including a function in a different file that causes Sinon to fail to be loaded in my JSDOM instance?

作为参考,这是我的renderedComponent初始化和FakeServer代码,坐在我的测试文件中:

test.js

renderedComponent = ReactTestUtils.renderIntoDocument(
      <Component...>
        <p>Drag &amp; drop files here or click here to browse for files.</p>
      </Component> 


... 

describe('Testing', function(){
    var server;

    before(function () { server = sinon.fakeServer.create(); });
    after(function () { server.restore(); });

    it("calls callback with deserialized data", function () {
        var callback = sinon.spy();
        renderedComponent.getTodos(callback);

        // This is part of the FakeXMLHttpRequest API
        server.requests[0].respond(
            200,
            { "Content-Type": "application/json" },
            JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
        );

        assert(callback.calledOnce);
    });

这是 renderedComponent 中的 serverRequest 函数,它是我正在尝试测试的不同文件中的React组件:

Component.js

var Component = React.createClass({

...

    function getTodoscallback) {
        $.ajax({
             url: "/todo/items",
             success: function (data) {
                 // Node-style CPS: callback(err, data)
                 callback(null, data);
             }
        });
    }
}

error 参数添加到AJAX请求会显示jsdom节点模块尝试执行 urlObj = new URL(uri, documentBaseURLSerialized(this._ownerDocument)); 时的语法错误

我的预感是这与JSDom加载jQuery和Sinon有关,但除此之外我不知道 - 我会感激任何帮助 .

1 回答

  • 0

    好吧,我设法用这个设置来解决它:

    import jsdom from 'jsdom';
    import _$ from 'jquery';
    
    global.jsdom = jsdom.jsdom;
    global.document = global.jsdom('<!doctype html><html><body></body></html>');
    global.window = global.document.defaultView;
    global.XMLHttpRequest = global.window.XMLHttpRequest;
    global.navigator = window.navigator;
    
    global.sinon = require('sinon');
    global.sinon.useFakeXMLHttpRequest();
    
    global.window.XMLHttpRequest = global.XMLHttpRequest;
    global.$ = _$(global.window);
    

    问题似乎是我需要将jQuery和sinon都设置为全局变量 . 仍然不完全确定,但感谢它的工作 .

相关问题