首页 > mocha 测试$.ajax 时报错?

mocha 测试$.ajax 时报错?

报错信息

  _jquery2.default.ajax({
                     ^

TypeError: _jquery2.default.ajax is not a function

如果输出jquery时存在的. 本身应用程序运行也是正常的.只是mocha时会报上面的的错误.


感谢回复.


你用 node --debug-brk 调试下 mocha跑的用例吧。我记得好像要引入依赖的外部库。
我没用mocha做过浏览器端的测试,翻了下官方文档,你试试看下面的写法 mocha.globals(['jQuery']);

<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
  <div id="mocha"></div>

  <script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script>
  <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
  <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>

  <script>mocha.setup('bdd')</script>
  <script src="test.array.js"></script>
  <script src="test.object.js"></script>
  <script src="test.xhr.js"></script>
  <script>
    mocha.checkLeaks();
    mocha.globals(['jQuery']);
    mocha.run();
  </script>
</body>
</html>

我是在命令行操作的不知为何不行. jquery任何方法都是undefined.


你需要安装一个 mocha-phantomjs,用mocha在命令行中,他没有 window document 等对象...,所以你安装mocha-phantomjs相当有一个没有界面的浏览器,浏览器相关对象你都可以获取赋值.....

你可以看我这里面怎么写测试用例的https://github.com/JSLite/JSLite

<!DOCTYPE html>
<html>
<head>
    <title>单元测试JSLite</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
    <!-- I you use Backbone Model you will need JSON -->
    <div id="mocha"></div>
    <script type="text/javascript" src="../dist/JSLite.js"></script>
    <script type="text/javascript" src="../node_modules/chai/chai.js"></script>
    <script src="../node_modules/mocha/mocha.js" type="text/javascript" ></script>
    <script>mocha.setup('bdd')</script>
    <script src="unit/core.test.js"></script>
    <script src="unit/selectors.test.js"></script>
    <script>
        var expect = chai.expect;
        var assert = chai.assert;
        if (window.mochaPhantomJS) {
            mochaPhantomJS.run();
        } else {
            mocha.run();
        }
    </script>
    <div id="test"></div>
</body>
</html>
【热门文章】
【热门文章】