使用JSON响应测试Ajax调用会返回意外的令牌

问题描述 投票:0回答:1

我有一个Vue应用程序,代码如下......

var vm = new Vue({
el: '#Workbooks',
components: {
    'workbook-list': workbooklist
},
data: {
    workbooks: [],
    message: '',
    loading: true,
    error: false
},
mounted: function () {
    this.getWorkbooks();
},
methods: {
    getWorkbooks: function () {
        var that = this;
        $.ajax({
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '/LandingPage/getWorkbooks',
            success: function (response) {
                var results = JSON.parse(response);
                that.workbooks = results.workbooks.workbook;
                that.checkResults();
            },
            error: function (xhr, exception) {
                that.loading = false;
                that.message = 'Sorry, there was a problem fetching your reports. Please try later.';
                that.error = true,
                console.log(xhr.status + ' ' + exception);
            },

        });
    },
     checkResults: function() {
        this.workbooks.length ? this.loading = false : this.message = 'You currently do not have any reports set up.';
    }
},

});

一切正常,但我想在成功的AJAX调用上测试它正在做它应该做的事情。

我有以下通过Karma运行的Jasmine代码...

it('should check the results on Ajax success', function () {
    spyOn(vm, "checkResults");
    spyOn($, 'ajax').and.callFake(function (e) {
        e.success({}); 
    });

    vm.getWorkbooks();

    expect("checkResults").toHaveBeenCalled();
});

我有两个问题。一个是我在AJAX URL上的日志中遇到404错误(它指向ASP.NET MVC控制器,而不是物理文件)。第二个是测试失败,出现'SyntaxError:位于1的JSON中的意外令牌o'。我假设这是因为它现在只是返回一个对象并且它试图解析不存在的JSON?如果我错了,请纠正我。

我的问题是如何解决这个问题以及对这些AJAX调用进行单元测试的正确方法是什么,因为我显然缺少某些东西?基本上我只是想以某种方式嘲笑那个回应。

我不知道是否值得注意的是我独立使用这些工具,所以我没有使用像Webpack这样的东西将各种东西捆绑在一起并运行它们。

非常感谢任何帮助。

ajax asp.net-mvc vue.js jasmine karma-runner
1个回答
0
投票

在下面的代码中你需要;而不是,

that.loading = false;
that.message = 'Sorry, there was a problem fetching your reports. Please try later.';
that.error = true; // on this line need ';' not ','
console.log(xhr.status + ' ' + exception);
© www.soinside.com 2019 - 2024. All rights reserved.