独立茉莉花中的辅助函数

helper functions in jasmine standalone

我有一个 Spec 文件单元测试了一堆方法。在同一个文件中,我有辅助函数。有没有办法将辅助函数移动到带有 jasmine standalone 和 vanilla js 的单独文件中?

  describe('#formatDateAndTime', () => {
    it('formats the date and time as per the requirements', () => {
      expect(till._formatDateAndTime()).toEqual(timeAndDate());
    });
  });

  function timeAndDate () {
    let today = new Date();
    return [today.getFullYear() + '.' + (today.getMonth() + 1) + '.' +
    today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() +
    ':' + today.getSeconds()];
  }

如何将 timeAndDate() 函数移动到辅助文件

使用 Jasmine 独立版,您 link 到 html 文件中的所有脚本 — 让我们称之为 tests.html。假设您的测试用例在 Tests.js 中,而您将助手放在 TestUtils.js.

您可以在 HTML 文件中执行以下操作:

tests.html

<html>
    <head>
        <title>Tests</title>
        
        <!-- Jasmine -->
        <link rel="shortcut icon" type="image/png" href="jasmine/lib/jasmine-3.3.0/jasmine_favicon.png">
        <link rel="stylesheet" type="text/css" href="jasmine/lib/jasmine-3.3.0/jasmine.css">
        <script type="text/javascript" src="jasmine/lib/jasmine-3.3.0/jasmine.js"></script>
        <script type="text/javascript" src="jasmine/lib/jasmine-3.3.0/jasmine-html.js"></script>
        <script type="text/javascript" src="jasmine/lib/jasmine-3.3.0/boot.js"></script>

        <!-- All scripts you want to test -->
        <script src='MyCoolProgram.js'></script>

        <!-- Specs -->
        <script src='TestUtils.js'></script>
        <script src='Tests.js'></script>
    </head>
</html>

然后,只需在浏览器中打开该文件,您应该能够根据需要看到您的测试 运行。

小心!如果你想Tests.js必须把TestUtils.js放在Tests.js之前调用 TestUtils.js 辅助方法。这是因为在 HTML 中,静态包含的脚本是按照它们在文件中出现的顺序注入的。