你如何在浏览器中运行mocha测试? [英] How do you run mocha tests in the browser?

查看:294
本文介绍了你如何在浏览器中运行mocha测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是我,或他们的文档没有解释如何完全在浏览器中运行测试?

Is it just me, or does their documentation not explain how to run the tests in the browser at all?

我是否必须创建他们在示例中显示的HTML文件?那么我如何使它为我的项目运行我的特定测试用例集?

Do I have to create that HTML file that they show in the example? How do I make it run my specific set of test cases for my project then?

我想要与运行 mocha 来自项目根目录。需要包含 test 文件夹中的所有子目录

I want the same output as running mocha from project root. All subdirectories inside the test folder need to be included

推荐答案

如果我们需要在浏览器中运行我们的测试,我们需要设置一个简单的HTML页面作为我们的测试运行页面。该页面加载了Mocha,测试库和我们的实际测试文件。要运行测试,我们只需在浏览器中打开跑步者。

If we need to run our tests in a browser, we need to set up a simple HTML page to be our test runner page. The page loads Mocha, the testing libraries and our actual test files. To run the tests, we’ll simply open the runner in a browser.

示例html代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Mocha Tests</title>
    <link rel="stylesheet" href="node_modules/mocha/mocha.css">
  </head>
  <body>
    <div id="mocha"></div>
    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/chai/chai.js"></script>
    <script>mocha.setup('bdd')</script>

    <!-- load code you want to test here -->

    <!-- load your test files here -->

    <script>
      mocha.run();
    </script>
  </body>
</html>

设置目录结构

你应该将测试放在与主代码文件不同的目录中。这样可以更容易地构建它们,例如,如果您希望将来添加其他类型的测试(例如集成测试或功能测试)。

You should put your tests in a separate directory from your main code files. This makes it easier to structure them, for example if you want to add other types of tests in the future (such as integration tests or functional tests).

最受欢迎使用JavaScript代码练习是在项目的根目录中有一个名为test /的目录。然后,每个测试文件都放在test / someModuleTest.js下。

The most popular practice with JavaScript code is to have a directory called test/ in your project’s root directory. Then, each test file is placed under test/someModuleTest.js.

重要的事情:


  • 我们加载Mocha的CSS样式,以便为我们的测试结果提供良好的格式。

  • 我们创建一个ID为mocha的div。这是测试结果插入
    的地方。

  • 我们加载了Mocha和Chai。它们位于
    node_modules文件夹的子文件夹中,因为我们通过npm安装它们。

  • 通过调用mocha.setup,我们可以使Mocha的测试助手可用。

  • 然后,我们加载要测试的代码和测试文件。我们现在还没有

  • 最后,我们调用mocha.run来运行测试。确保在加载源文件和测试文件后调用此

  • We load Mocha’s CSS styles to give our test results nice formatting.
  • We create a div with the ID mocha. This is where the test results are inserted.
  • We load Mocha and Chai. They are located in subfolders of the node_modules folder since we installed them via npm.
  • By calling mocha.setup, we make Mocha’s testing helpers available.
  • Then, we load the code we want to test and the test files. We don’t have anything here just yet.
  • Last, we call mocha.run to run the tests. Make sure you call this after loading the source and test files

这篇关于你如何在浏览器中运行mocha测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆