javascript - 使用 grunt 在静态服务器上运行 Qunit 测试时遇到问题

标签 javascript node.js gruntjs qunit grunt-contrib-connect

通过网络浏览器运行测试工作正常,但使用 grunt 会出现错误。我很难理解我在这里做错了什么。 grunt 测试 失败并显示

$ grunt tests
Running "jsonlint:sample" (jsonlint) task
>> 4 files lint free.

Running "jshint:all" (jshint) task
>> 4 files lint free.

Running "connect:server" (connect) task
Started connect web server on http://localhost:5000

Running "qunit:all" (qunit) task
Testing http://localhost:5000/tests/tests.html F
>> Settings.json tests - Fetching settings file
>> Message: InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.
>> Actual: null
>> Expected: undefined
>> http://localhost:5000/tests/tests.js:7

>> Settings.json tests - Fetching settings file
>> Message: Check settings JSON file
>> http://localhost:5000/tests/tests.js:25:24
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

>> Settings.json tests - Fetching settings file
>> Message: Assertion after the final `assert.async` was resolved
>> Actual: null
>> Expected: undefined
>> notEqual@http://localhost:5000/tests/qunit/qunit-1.22.0.js:1512:18
>> http://localhost:5000/tests/tests.js:25:24
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

>> Settings.json tests - Fetching settings file
>> Message: Check settings JSON file
>> http://localhost:5000/tests/tests.js:25:24
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

>> Settings.json tests - Fetching settings file
>> Message: Too many calls to the `assert.async` callback
>> Actual: null
>> Expected: undefined
>> http://localhost:5000/tests/tests.js:26:13
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

>> Settings.json tests - Fetching settings file
>> Message: Assertion after the final `assert.async` was resolved
>> Actual: null
>> Expected: undefined
>> notEqual@http://localhost:5000/tests/qunit/qunit-1.22.0.js:1512:18
>> http://localhost:5000/tests/tests.js:25:24
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

>> Settings.json tests - Fetching settings file
>> Message: Check settings JSON file
>> http://localhost:5000/tests/tests.js:25:24
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

>> Settings.json tests - Fetching settings
>> Message: Too many calls to the `assert.async` callback
>> Actual: null
>> Expected: undefined
>> http://localhost:5000/tests/tests.js:26:13
>> onreadystatechange@http://localhost:5000/tests/tests.js:8:25

Warning: 8/8 assertions failed (54ms) Use --force to continue.

Aborted due to warnings.

Gruntfile.js

module.exports = function(grunt) {
  grunt.initConfig({
    jsonlint: {
      sample: {
        src: ['json/*.json', 'api_files/*.json'],
        options: {
          formatter: 'prose'
        }
      }
    },
    jshint: {
      all: ['*.js', 'tests/*.js', 'server/*.js']
    },
    connect: {
      server: {
        options: {
          port: 5000,
          base: '.'
        }
      }
    },
    qunit: {
      all: {
        options: {
          urls: [
            'http://localhost:5000/tests/tests.html'
          ]
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-jsonlint');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-qunit');

  grunt.registerTask('tests', ['jsonlint', 'jshint', 'connect', 'qunit']);
};

测试.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Backend Tests</title>
    <link rel="stylesheet" href="qunit/qunit-1.22.0.css">
    <script src="qunit/qunit-1.22.0.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="tests.js"></script>
</body>
</html>

测试.js

var HttpClient = function () {
    this.get = function (requestUrl, callback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function () {
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200) {
                callback(anHttpRequest.responseText);
            } else if (anHttpRequest.status == 404) {
                callback(null);
            }
        };

        anHttpRequest.open("GET", requestUrl, true);
        anHttpRequest.send(null);
    };
};

var rootUrl = "http://localhost:5000";
var client = new HttpClient();

QUnit.module("Fetching settings.json");

QUnit.test('Fetching settings file', function (assert) {
    var done = assert.async();
    client.get(rootUrl + '/api/settings', function (response) {
        assert.notEqual(response, null, 'Check settings JSON file');
        done();
    });
});

main.js

function serveStaticFiles(router) {
    var app = express();
    app.use('/api', router);                // all of our routes will be prefixed with /api
    app.use('/', express.static(__dirname + '/')); // Makes it possible for html files to fetch images from img
    app.use(express.static('./html'));      // folder 'html' is now considered public and accessible
    app.use(express.static('./xml'));       // folder 'xml' is now considered public and accessible
    app.use(express.static('./img'));       // folder 'img' is now considered public and accessible
    app.use(express.static('./json'));      // folder 'json' is now considered public and accessible
    app.use(express.static('./tests'));     // folder 'tests' is now considered public and accessible

    return app;
}

var bugsnag = require("bugsnag");
bugsnag.register(process.env.BUGSNAG_API_KEY);
bugsnag.releaseStage = process.env.BUGSNAG_RELEASE_STAGE;
bugsnag.notifyReleaseStages = ["stage", "production"];

var express = require('express');
var router = express.Router();
var app = serveStaticFiles(router);
var port = process.env.PORT || 5000;
var server = app.listen(port);
var apiHandler = require("./server/ApiHandler");
console.log("Application created and it listens on port " + port);

apiHandler.initRestApi(router);

最佳答案

您需要运行 Node 服务器作为 grunt 流程中的另一个步骤。有一个具体的 grunt 任务 running Express servers ,我建议从那里开始。 grunt 配置可能如下所示:

grunt.initConfig({
    // ...
    express: {  // this is the new task...
      dev: {
        options: {
          script: 'path/to/main.js'
        }
      }
    },
    connect: {
      server: {
        options: {
          port: 3000,  // I changed this so it doesn't conflict with your express app
          base: '.'
        }
      }
    },
    qunit: {
      all: {
        options: {
          urls: [
            'http://localhost:3000/tests/tests.html'  // changed this as well
          ]
        }
      }
    }
});

然后,您将需要在“测试”运行时运行所有三个任务。您可以像这样创建别名:

grunt.registerTask('tests', ['jsonlint', 'jshint', 'express', 'connect', 'qunit']);

关于javascript - 使用 grunt 在静态服务器上运行 Qunit 测试时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41490519/

相关文章:

javascript - 如何使用javascript删除html标签之间的空白?

javascript - 刷新后在网站上运行 javascript

javascript - 有没有办法在 JavaScript 中测试循环引用?

javascript - 如何在纯 JavaScript 中使 node.js 需要函数

mysql - nodejs连接mysql报错

gruntjs - 如何使用 grunt-contrib-concat 和 grunt-contrib-uglify 为每个单独的 js 文件创建源映射?

javascript - 在 fadeOut 完成之前触发回调

javascript - Greasemonkey 可以从分页的 URL 序列中获取值吗?

gruntjs - 本地主机上的 Grunt Livereload 以 WAMP/XAMPP/UniServerZ 启动

gruntjs - 咕噜声丑化。如何缩小并用结果替换原始文件?