grunt-mocha - $ .get内的断言失败

时间:2016-08-18 12:52:02

标签: javascript unit-testing gruntjs phantomjs mocha

我正在尝试使用requireJS连接grunt-mocha进行一些单元测试,它运行良好,除了我似乎无法测试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调用不兼容,但我无法弄明白。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

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

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

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

请注意webSecurityEnabled选项。