【问题标题】:grunt-mocha - assertion inside $.get failsgrunt-mocha - $.get 中的断言失败
【发布时间】:2016-08-18 12:52:02
【问题描述】:

我正在尝试将 grunt-mocha 与 requireJS 连接起来进行一些单元测试,效果很好,但我似乎无法测试 ajax 调用。

我有一个代码库:https://bitbucket.org/IamHttP/grunt-mocha-tests/overview

具体文件可以找到here

代码本身粘贴在这里:

describe('testJqueryAjax', function(){

    it('fetch data from an xhr', function(done){
        this.timeout(3000);

        require(['jquery'],function($){

            $.ajax({
                url: 'https://api.github.com',
                success: function(str){
                    try{
                        chai.assert.equal( 1 , 1 );
                        done();
                    }
                    catch(e){
                        done(e);
                    }
                }
            }).fail(function(){
                try{
                    chai.assert.ok( false );
                    done();
                }
                catch(e){
                    done(e);
                }
            });

        });
    });
});

问题:

无论我指向哪里,ajax 请求总是失败。 .fail 函数总是被调用。

我猜这是 phantomJS 不能很好地与 jQuery 的 $.ajax 调用一起工作的问题,但我想不通。

感谢任何帮助!

【问题讨论】:

  • 如果您怀疑 PhantomJS 是问题所在,您是否尝试在真实浏览器中加载测试?这是我要尝试的第一件事。
  • 谢谢,怀疑,它在浏览器上工作正常,我猜这是一个 phantomJS 问题

标签: javascript unit-testing gruntjs phantomjs mocha.js


【解决方案1】:

已通过向 phantomJS 添加配置选项解决了该问题。

这是使用 mocha 的 grunt 任务完成的:

    mocha : {
        all : {
            src : ['tests/testrunner.html']
        },
        options : {
            run: true,
            page: {
                settings: {
                    webSecurityEnabled: false,  // disable cors checks in phantomjs
                },
            },
        },

注意 webSecurityEnabled 选项。

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2011-05-27
    • 2017-08-07
    • 2012-08-01
    相关资源
    最近更新 更多