2017-01-05 3 views
1

Выполнение тестов через веб-браузер отлично работает, но использование grunt дает мне ошибки. Я изо всех сил пытаюсь понять, что я делаю неправильно. grunt tests терпит неудачу сНеисправность при запуске тестов Qunit со статическим сервером с использованием 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 
>> [email protected]://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 
>> [email protected]://localhost:5000/tests/qunit/qunit-1.22.0.js:1512:18 
>> http://localhost:5000/tests/tests.js:25:24 
>> [email protected]://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 
>> [email protected]://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 
>> [email protected]://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 
>> [email protected]://localhost:5000/tests/qunit/qunit-1.22.0.js:1512:18 
>> http://localhost:5000/tests/tests.js:25:24 
>> [email protected]://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 
>> [email protected]://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 
>> [email protected]://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']); 
}; 

tests.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> 

tests.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); 
+0

Что делать, если код состояния не 200 или 404? В этом случае «обратный вызов» не будет запущен. Я бы удостоверился, что у вас есть catchout в вашем событии 'onreadystatechange':' else if (anHttpRequest.readyState> = 4) {callback (null)} ' – jakerella

+0

@jakerella. Вы правы, конечно, спасибо. Однако это не причина ошибок, которые я получаю. Вы понимаете ошибки и их причину? – MdaG

+0

Поскольку это ошибка 404, я предполагаю, что соединение grunt-contrib-ist не работает так, как ожидалось? – MdaG

ответ

1

Вам нужно будет запустить сервер узлов как еще один шаг в вашем процессе хрюкания. Существует задание на ворчание для специально running Express servers, я бы рекомендовал начать там. Вот что хрюканье конфигурация может выглядеть следующим образом:

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']);

+0

А, спасибо. Я должен был явно установить порт на 5000 в опциях экспресс-dev, или ему будет назначено 3000, и это не соответствует требованиям rootUrl в тестах. Мне также пришлось изменить порт URL-адреса qunit на то же, что и express (5000), или он просто отключится. Тем не менее, я все еще получаю 404 при попытке получить данные. Похоже, что он очистил всю ошибку, кроме 'InvalidStateError: DOM Exception 11: была сделана попытка использовать объект, который не является или больше не используется. '. Огромный шаг в правильном направлении. Спасибо. :) – MdaG