Qunit parameterized tests and mocking

后端 未结 5 981
一生所求
一生所求 2020-12-23 09:38

I have two questions:

Can you have parameterised unit tests in qunit?

How do you do mocking with qunit e.g. mocking a getJSON c

5条回答
  •  旧巷少年郎
    2020-12-23 10:11

    Instead of overriding jQuery's AJAX function, you could also use the jQuery Mockjax plugin developed by .appendTo. This plugin essentially does what the other answer suggests, but it allows for much more sophisticated mocking. For example, if you have the function:

    $.ajax({
        url:"/api/user",
        type:"GET",
        dataType:"json",
        data:'{"uid":"foobar"}',
        success:function(data){
            console.log("Success!");
        },
        error:function(data){
            console.log("Error!");
        }
    });
    

    You can mock it with mockjax by simply calling the function mockjax, which is automatically included in jQuery:

    $.mockjax({
        url:"/api/user",
        type:"GET",
        response:function(requestData){
             //handle the mock response in here
             this.responseText = '{"fullname":"Mr. Foo Bar"}';
        }
    });
    

    The second mocking function can be included in an external JavaScript file, say "mocks.js," and the only other thing that needs to be done is include the mockjax library (which can be found at https://github.com/appendto/jquery-mockjax/). The only thing to keep in mind is that this will only mock jQuery ajax calls, not all XMLHttpRequests. If you want to do that, then follow @bertvh's advice and use Sinon.js.

提交回复
热议问题