如何在Mocha/Chai中测试JS原型(非模块)

How do I test JS prototypes (non-modules) in Mocha/Chai?

本文关键字:原型 JS 模块 测试 Mocha Chai      更新时间:2023-09-26

我想为我正在构建的项目设置测试。在我能找到的例子中,他们都说包括要测试的相关代码是通过一个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({});
  });
});

如果你不使用模块,你可以为你的测试创建一个简单的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>

这样,您就不需要在测试文件中要求某些内容。

如果你想要更多信息:文章

我希望它能帮助你。