如何参考另一个 class 创建 QUnit 测试?

How to create QUnit tests with reference to another class?

我正在尝试将 JavaScript 的单元测试添加到我的网站中。我使用 VS2013,我的项目是一个 ASP.NET 网站。

根据建议 (http://www.rhyous.com/2013/02/20/creating-a-qunit-test-project-in-visual-studio-2010/),我目前已完成:

  1. 创建了新的 ASP.NET 应用程序
  2. 导入 QUnit(使用 NuGet)
  3. Into "Scripts" 在我的原始网站中添加了指向 js 文件的链接(文件 PlayerSkill.js - 包含 PlayerSkill class 和 trainings.js - 包含 Trainer 和其他一些 classes)
  4. 已创建新文件夹"TestScripts"
  5. 已添加 TrainingTests.js 文件
  6. 写了简单的测试:

     test( "Trainer should have non-empty group", function () {
        var group = "group";
        var trainer = new Trainer(123, "Name123", group, 123);
        EQUAL(trainer.getTrainerGroup(), group);
     });
    

注意:我的 trainings.js 文件等包含

function Trainer(id, name, group, level) {
    ... 
    var _group = group;
    this.getTrainerGroup = function () { return _group ; }
};

当我执行测试时,我看到错误:Trainer is not defined。

似乎无法识别对我的 class 的引用。我觉得链接文件还不够,但是我错过了什么?

请使用class和运行单元测试帮助添加对原始文件的引用。

谢谢。

P.S。问题 2:我可以添加对 2 个文件的引用吗(我的单元测试将需要一个 class,它在另一个文件中)?怎么样?

您应该将应用程序的所有相关逻辑添加到您的单元测试文件中,以便它们都在 您 运行 您的测试

之前执行
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>QUnit Test Results</title>
        <link rel="stylesheet" href="/Content/qunit.css">
    </head>
    <body>
        <div id="qunit"></div>
        <div id="qunit-fixture"></div>
        <script src="/Scripts/qunit.js"></script>
        <script src="/Scripts/PlayerSkill.js"></script>
        <script src="/Scripts/trainings.js"></script>
        <script src="/TestScripts/TrainingTests.js"></script>
    </body>
</html>

不应该使用链接文件,因为它们不会实际存在于脚本文件夹中。

如果你真的想使用它们,你应该让 Visual Studio intellisense 像这样解析文件的物理路径。

  1. 键入脚本标记 <script src=""></script>
  2. 将光标放在 src 属性的引号内,然后按 CTRL + SPACE
  3. 搜索您的文件并保留已解析的路径
  4. 如果您的项目位置发生变化,您必须更新链接文件以及脚本引用。

{编辑1}

解决方案 2:

您还可以使用 MVC 控制器和 Razor 视图来创建单元测试页面,链接文件将按预期工作,唯一的问题是您的项目中将有一个额外的控制器,但这在all 例如,如果您想使用 ajax 测试内容的加载,如果它们是 运行 来自本地文件,默认情况下会被浏览器阻止。

解决方案 3:

您还可以为 javascript 单元测试设置一个新的 MVC 项目,就像您通常为任何服务器端代码设置一个新项目一样,这将有助于防止您的测试干扰您的生产代码

{编辑 2}

解决方案 4:

作为 javascript 生态系统的一部分,您可以使用 g运行t 或 gulp 在 运行ning 之前自动将脚本从任何地方复制到您的项目测试。你可以这样写 gulpfile.js

var sourcefiles = [/*you project file paths*/];
gulp.task('default', function () {
    return gulp.src(sourcefiles).pipe(gulp.dest('Scripts'));
});

然后 运行 它打开一个控制台并 运行 输入命令 gulpgulp default

看起来 trainings.js 在调用 TrainingTests.js 时没有定义。参见 this question for more details regarding why this happens! Once that is fixed it does work. And yes similar to trainings.js you can have any number of files in any folder as long as you reference them properly. I have created a sample fiddle accessible @ http://plnkr.co/edit/PnqVebOzmPpGu7x2qWLs?p=preview

<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="http://code.jquery.com/qunit/qunit-1.18.0.js"></script>
  <script src="trainings.js"></script>
  <script src="TrainingTests.js"></script>
</body>

好吧,由于两个答案的帮助,我确实本地化了这个问题确实是因为 VS 无法将所需的文件复制到测试项目中。

这大概可以通过多种方式解决,我找到了一个,思路复制自:http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

解决方法很简单:动态添加标签

为了实现这一点,我在标签中添加了以下代码:

<script>
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    var path = 'path'; // here is an absolute address to JS-file on my web site
    fileref.setAttribute("src", path);
    document.getElementsByTagName("head")[0].appendChild(fileref);

    loadjscssfile(, "js") //dynamically load and add this .js file
</script>

并将我的测试移入(还需要参考之前的 jquery)

    $(document).ready(function () {
        QUnit.test("Test #1 description", function () { ... });
    });

类似的方法也适用于纯测试文件。

In my case I wanted to run my tests from within my ASP.NET web application, and also on a CI server. In addition to the other information here I needed the following, otherwise I experienced the same error as the OP on my CI server:

  1. 添加一个或多个 require() 测试脚本调用。
  2. NODE_PATH 环境变量设置为我的应用程序的根目录。

require()

的例子

在我的测试脚本中,我包含了一个 requires 块,条件允许我从网络浏览器使用这个脚本,而不需要采用 third-party 等价物,例如 requirejs(这很方便。)

if (typeof(require) !== 'undefined') {
    require('lib/3rdparty/dist/3p.js');
    require('js/my.js');
    require('js/app.js');
}

设置示例NODE_PATH

下面,'wwwroot'/lib/等应用文件所在的路径。我的测试文件位于 /tests/.

使用bash

#!/bin/bash
cd 'wwwroot'
export NODE_PATH=`pwd`
qunit tests

使用powershell

#!/usr/bin/pwsh
cd 'wwwroot'
$env:NODE_PATH=(pwd)
qunit tests

这使我能够 运行 在我的 ASP.NET 网络应用程序中以及使用脚本从 CI 服务器进行测试。

HTH.

如果您想知道如何在从命令行(而不是浏览器!)运行时让您的测试看到您的代码,这里是 Shaun Wilson[的扩展版本 的答案(不是开箱即用的,但包含从哪里开始的好主意)

具有以下结构:

project
│   index.js <--- Your script with logic
└───test
        tests.html <--- QUnit tests included in standard HTML page for "running" locally
        tests.js <--- QUnit test code

让我们想象一下,在您的 index.js 中,您有以下内容:

function doSomething(arg) {
  // do smth
  return arg;
}

tests.js 中的测试代码(并不是说它可以是文件的 全部 内容 - 您不需要任何其他内容即可工作):

QUnit.test( "test something", function( assert ) {
  assert.ok(doSomething(true));
});

运行 来自命令行

为了让您的代码可以从测试中访问,您需要向脚本添加两件事

首先是从测试中显式 "import" 您的脚本。由于 JS 没有开箱即用的功能,我们需要使用来自 NPM 的 require。为了让我们的测试从 HTML 开始工作(当你从浏览器 运行 它时,require 是未定义的)添加简单的检查:

// Add this in the beginning of tests.js
// Use "require" only if run from command line
if (typeof(require) !== 'undefined') {
    // It's important to define it with the very same name in order to have both browser and CLI runs working with the same test code
    doSomething = require('../index.js').doSomething;
}

但是如果index.js不公开任何东西,就无法访​​问任何东西。因此需要显式公开要测试的函数(阅读有关 exports 的更多信息)。将此添加到 index.js:

//This goes to the very bottom of index.js
if (typeof module !== 'undefined' && module.exports) {
  exports.doSomething = doSomething; 
}

完成后,只需输入

qunit

输出应该是这样的

TAP version 13
ok 1 Testing index.js > returnTrue returns true
1..1
# pass 1
# skip 0
# todo 0
# fail 0