【问题标题】:helper functions in jasmine standalone茉莉花独立中的辅助功能
【发布时间】:2018-12-28 21:33:23
【问题描述】:

我有一个 Spec 文件单元测试一堆方法。在同一个文件中,我有辅助函数。有没有办法使用 jasmine 独立和 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() 函数移动到帮助文件中

【问题讨论】:

标签: javascript jasmine helper


【解决方案1】:

使用 Jasmine 独立版,您可以链接到一个 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 辅助方法,则必须将 TestUtils.js 放在 Tests.js 之前。这是因为在 HTML 中,静态包含的脚本是按照它们在文件中出现的顺序注入的。

【讨论】:

  • 嗨,谢谢你的回答,所以与其以 Spec 结束文件名,不如将其命名为 TestUtils.js?你是这个意思吗?并且我可以移动 TestUtils.js 文件中的所有辅助函数,如上面的示例所示?
  • 您可以为文件命名几乎任何您真正想要的名称,但重要的部分是在您的测试用例脚本之前将脚本与您的帮助函数一起包含在内。
猜你喜欢
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多