如何使用茉莉花测试功能内部的json? [英] How to test json inside function using jasmine?

查看:53
本文介绍了如何使用茉莉花测试功能内部的json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要测试的代码:

function loadNotification(searchOption, searchKey) {
   var url = '@URLs.API.Notifications.Past' + '?searchOption=' + searchOption + '&searchValue=' + searchKey;
   $.getJSON(url)
      .done(function (nData) {
        //some code here
      })
      .fail(function (jqXHR, status, error) {
        showError('There was an error while fetching the records. Please try after some time. (' + jqXHR.status + ':' + jqXHR.statusText + ')');
      });
}

使用茉莉花,如何测试 json 文件是否失败?我当时在考虑使用 .done .fail ,但不确定是否可行.我对 json 不太了解.有人可以帮我吗?

Using jasmine, how do I test if the json file fails or not? I was thinking of using .done and .fail but I'm not sure if it's possible. I don't know much about json. Can anyone help me out?

推荐答案

在测试AJAX请求(以及类似的获取json文件等)时,最好检查代码是否可以处理完成和失败.您还应该模拟测试的数据,不要过多依赖应用程序或尝试下载的文件中的实际端点.您希望测试尽可能快地运行.

when testing AJAX requests (and similar, fetching json file etc.), it's always a good idea to check that your code can handle both done and fail. You should also mock the data that you test, don't rely much on actual endpoints in your application or files that it tries to download. You want the test to run as fast as possible.

使用茉莉花,您可以做一些事情:

Using Jasmine you can do a few things:

使用间谍:

spyOn是一个函数,可以对给定的函数进行存根并跟踪传递给它的参数类型,可以查看其他函数调用了什么,甚至可以在执行被监视的代码时返回特定的值.

spyOn is a function that can stub a given function and track what kind of arguments were passed to it, can see what other function called it and even return a specific value when the code that it's spied on executes.

您可以使用间谍程序来查看$ .get请求的发生,然后可以说返回一个特定值,并继续测试该程序.

You could use a spy to see that the $.get request will happen, and then you can say return a specific value, and continue testing the program.

使用Jasmine Ajax插件

这就是我想在测试中使用的东西. Jasmine有一个非常不错的插件 ajax.js .它简化了对任何ajax功能的测试.我想做的是模拟实际的请求,因此当您的代码尝试获取文件/响应时,代码将忽略实际的调用并对其进行模拟,并返回您可以指定的伪造数据.

This is what I like to use in my tests. Jasmine has a very nice plugin ajax.js. It simplifies testing any ajax functionality. What I like to do is to mock the actual request, so when your code would tries to get a file/response, the code will ignore the actual call and mock it, returning fake data that you can specify.

在开始之前,我还喜欢将我的ajax方法放在单独的函数中,它只会返回一个promise.读取/测试/维护起来要容易得多,例如,您可以像这样重写它:

Before I start, I also like to have my ajax method in a separate function, it will just return a promise. It's much easier to read/test/maintain, so for example you could rewrite it like:

this.loadNotificationCall = function(searchOption, searchKey) {
    var url = '@URLs.API.Notifications.Past' + '?searchOption=' + searchOption + '&searchValue=' + searchKey;
    return $.getJSON(url)
} 

this.loadNotification() {
    return this.loadNotificationCall()
        .done(function (nData) {
            //some code here
        })
        .fail(function (jqXHR, status, error) {
            showError('There was an error while fetching the records. Please try after some time. (' + jqXHR.status + ':' + jqXHR.statusText + ')');
        });
}

如果您用虚拟数据加载测试应用程序,我猜您希望ajax请求文件具有特定路径.

If you load your test app with dummy data, I guess you expect the ajax request file to have a specific path.

您正在寻找可从

'@URLs.API.Notifications.Past' + '?searchOption=' + searchOption + '&searchValue=' + searchKey;

比方说

//'someapi?searchOption=1&searchValue=abc'

该网址必须与您的应用程序尝试联系的网址完全匹配.检查您的调试/提琴手,以防万一.如果不匹配(包括它尝试发送的数据),模拟将失败,并且测试将超时.该错误通常看起来像Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

That url needs to exactly match to what will your application would attempt to contact. Check your debug/fiddler and see what is that just in case. If it's not matched (including the data it's trying to send) the mock will fail, and test will timeout. The error usually looks like Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

一旦设置正确,就可以在以下示例中模拟该网址:

Once you get that right, you can mock that url in the following example:

describe('when user gets the data', function() {

var sut = null;
var testCall = null;
var dummyData = {
    name: 'Jon Snow'
};
beforeEach(function() {
    jasmine.Ajax.install();
    jasmine.Ajax.stubRequest("someapi?searchOption=1&searchValue=abc").andReturn({
            responseText: JSON.stringify(dummyData)
    });

    sut = new yourApplication();
    testCall = sut.loadNotification();
});

afterEach(function() {
    jasmine.Ajax.uninstall();
});

// actual tests here

});

我也非常确定您可以在这些模拟网址中使用通配符,因此这也应有效:jasmine.Ajax.stubRequest("someapi?(.*)").andReturn(//

I'm also pretty sure that you can use wildcards in those mock urls, so this should also be valid: jasmine.Ajax.stubRequest("someapi?(.*)").andReturn(//

所以现在发生的是,如果您测试将使用$ .get调用您的方法的东西,则服务器不会发生该请求,而是将模拟该请求并返回我们的虚拟数据.在此示例中,它是带有name: 'Jon Snow'

So what happens now is, if you test something that will call your method with $.get, the request won't happen to your server, but instead it will be mocked and our dummy data will be returned. In this example it's a simple object with name: 'Jon Snow'

现在,您想要进行如下所示的测试:

Now, you want to have a test that looks something like this:

it('should populate name', function(done) {
    testCall
        .done(function() {
            expect(sut.name).toEqual('Jon Snow');
            done();
        });
});

将done参数传递给测试,以便在调用完成之前它不会完成.如果在浏览器中对其进行调试,您将看到文件中的代码将进入done方法中,并按照实际请求继续工作. done(nData)中的数据将成为name: Jon Snow的虚拟对象.

You pass done argument to the test, so that it won't finish until the call is finished. If you debug it in your browser, you will see that code in your file will go inside done method and continue working as it was a real request. The data in done(nData) will become our dummy object with name: Jon Snow.

如果要测试失败的代码,可以向ajax插件添加一些其他设置:

If you wanted to test a failing code, you can add some additional settings to ajax plugin:

jasmine.Ajax.stubRequest("someapi?searchOption=1&searchValue=abc").andReturn({
    status: 500,
    responseText: "{}"
});

我希望我不会对您造成太多的麻烦,我知道有一些更简单的方法(例如,仅在'ajax'上执行$ .spy并查看最近的通话等),但是我喜欢我的方法,已经奏效了很好,我可以测试多个呼叫,链接的呼叫,以及更多更酷的场景.

I hope I didn't bore you with this much, I know that there are simplier methods (such as just doing $.spy on 'ajax' and seeing the most recent call etc. but I like my method, has worked very well and I can test multiple calls, chained calls, and many more cool scenarios.

这篇关于如何使用茉莉花测试功能内部的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆