【问题标题】:Script error (:0) when trying to run async test in mocha-phantomjs尝试在 mocha-phantomjs 中运行异步测试时出现脚本错误 (:0)
【发布时间】:2014-11-12 08:15:32
【问题描述】:

我正在尝试测试一段异步代码,但遗憾的是我得到了一个模糊的错误代码,我似乎无法弄清楚问题所在。测试在浏览器中运行良好,但在 phantomjs 中运行会导致:

Uncaught Script error. (:0)

测试被编写为一个 requirejs 模块,并且依赖于另一个模块。 就像我说的,这在浏览器中运行良好,并且在不进行异步测试时一切正常 在 phantomjs 中也很好。我正在使用 phantomjs 1.9.12 和 mocha-phantomjs 3.4.1。

define([ "csl" ], function( csl ) 
{  
   describe( "CSL", function()
   {
      it( "isLoggedIn", function( testCompleted )
      {
          csl.isLoggedIn().then( function( partner )
          {
              chai.expect( partner ).to.be.a( "object" );
              testCompleted();
          } )
          .fail( function( error )
          {
               testCompleted( error );
          } );
      } );
  } );
} );

【问题讨论】:

  • 使用PhantomJS 1.9.7-15的时候会出现吗?如果是,this 可能是相关的,因为 PhantomJS 1.9.12 是一个包含 PhantomJS 1.9.8 的 npm 包。
  • 我尝试使用 npm 包 PhantomJS 1.9.7-15,同样的问题。当使用 NPM 1.9.12 的最新版本时,问题仍然存在,但测试状态变为挂起而不是失败。虽然仍然抛出“脚本错误(:0)错误。所以这意味着我应该是1.9.8之前的幻影版本?
  • 在我的情况下,为来自同一来源的所有文件提供帮助。尽量不要使用 CDN 或 file: 方案。而是从单个服务器提供所有脚本。另见此处:github.com/mochajs/mocha/issues/165

标签: asynchronous requirejs phantomjs mocha.js mocha-phantomjs


【解决方案1】:

这是mocha在async函数出现异常时产生的错误,chai.expect可以抛出AssertionError。

您可以通过简单的超时在浏览器中重现相同的错误:

    it("should fail async", function(done) {
        window.setTimeout(function() {
            "".should.not.equal("");
            done();
        })
    })

要修复它,您需要通过回调而不是异常来报告错误:

    it("should fail async with good error", function(done) {
        window.setTimeout(function() {
            if ("" == "") return done(new Error("Async error message"));
            done();
        })
    })

    it("should fail async with exception", function(done) {
        window.setTimeout(function() {
            try {
                "".should.not.equal("");
            }
            catch (e) {
                return done(e);
            }
            done();
        })
    })

问题不在于 phantom 本身(除了导致测试失败的任何原因),而是测试运行程序和 phantom 之间的连接使一切都异步,从而触发了 mocha 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 2021-06-09
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2012-09-29
    相关资源
    最近更新 更多