【问题标题】:How do I test JS prototypes (non-modules) in Mocha/Chai?如何在 Mocha/Chai 中测试 JS 原型(非模块)?
【发布时间】:2015-04-06 17:00:30
【问题描述】:

我想为我正在构建的项目设置测试。在我能找到的示例中,他们都说包含要测试的相关代码是由 require 语句完成的:require('foo');。但是我的项目不是在模块中构建的,而是在 ES6 类中构建的,然后将其转换为 ES5 原型。

我想知道如何包含文件?

例如 ES6 类:

class Foo {
  constructor() {
    // do things
  }
}

大致翻译为:

// ES5 compatible code is here (_classCallCheck etc).
var Foo = (function () {    
  function Foo() {
    _classCallCheck(this, Foo);

   // do things
  }
}

我想知道如何将它包含在我的测试文件中:

var expect   = require('chai').expect;
// how to require or whatever else here?

describe('Foo', function() {
  it('creates an Foo object', function() {
    var foo = new Foo({});
  });
});

【问题讨论】:

    标签: javascript unit-testing testing mocha.js chai


    【解决方案1】:

    如果你不使用模块,你可以像这样为你的测试创建一个简单的 html 页面:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>your tests</title>
      <link rel="stylesheet" media="all" href="vendor/mocha.css">
    </head>
    <body>
      <div id="mocha"><p><a href=".">Index</a></p></div>
      <div id="messages"></div>
      <div id="fixtures"></div>
      <script src="vendor/mocha.js"></script>
      <script src="vendor/chai.js"></script>
      <script src="your_files.js"></script>
      <script src="your_files_test.js"></script>
      <script>mocha.run();</script>
    </body>
    </html>
    

    有了这个,你就不需要在你的测试文件中添加任何东西了。

    如果您想了解更多信息:article

    希望对你有帮助。

    【讨论】:

    • 谢谢,你把我送到了正确的方向。我也在使用 Grunt,所以使用 this articlegrunt-mocha-phantomjs 插件,我可以很容易地实现我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多