2015-04-03 2 views
10

Я пытаюсь настроить среду QUnit с помощью requirejs и grunt-contrib-qunit.Как настроить задачу grunt для requirejs и qunit

Вот что у меня есть.

gruntfile:

qunit: { 
    all: { 
    options: { 
     urls: [ 
     'http://localhost:8000/qunit/qunit-test-suite.html' 
     ] 
    } 
    } 
}, 

connect: { 
    server: { 
    options: { 
     port: 8000, 
     base: '.' 
    } 
    } 
}, 

QUnit-тест-suite.html:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>QUnit Tests Suite: travis CI Test</title> 
    <link rel="stylesheet" href="../components/libs/qunit/qunit/qunit.css"> 
</head> 
<body> 

    <div id="qunit"></div> 
    <div id="qunit-fixture"></div> 

    <script src="../components/libs/qunit/qunit/qunit.js"></script> 
    <script> 
    QUnit.config.autoload = false; 
    QUnit.config.autostart = false; 
    </script> 

    <script data-main="qunit" src="../components/libs/requirejs/require.js"></script> 

</body> 
</html> 

qunit.js:

require.config({ 
    baseUrl: "../", 
    paths: { 
     'jquery': 'components/libs/jquery/dist/jquery.min', 

     // Test for Foo 
     'foo': 'components/app/foo/foo', 
     'test-Foo': 'components/app/foo/test-Foo' 
    }, 
    shim: { 
    'QUnit': { 
     exports: 'QUnit', 
     init: function() { 
     QUnit.config.autoload = false; 
     QUnit.config.autostart = false; 
     } 
     } 
    } 
}); 

require(['test-Foo'], function (Foo) { 
    QUnit.load(); 
    QUnit.start(); 
}); 

тест-foo.js:

define(['foo'], function(Foo) { 

    'use strict'; 

    module("Foo"); 

    test("Foo return Test", function() { 
    equal(Foo.foo(), "foo", "Function should return 'foo'"); 
    equal(Foo.oof(), "oof", "Function should return 'oof'"); 
    }); 

    test("Bar return Test", function() { 
    equal(Foo.bar(), "barz", "Function should return 'bar'"); 
    }); 

}); 

Проблема в том, что все работает нормально, когда я открываю test-suite.html в своем браузере. После отправки в PhantomJS я получаю следующее сообщение об ошибке:

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

Running "qunit:all" (qunit) task 
Testing http://localhost:8000/qunit/qunit-test-suite.html 

>> PhantomJS timed out, possibly due to a missing QUnit start() call. 
Warning: 1/1 assertions failed (0ms) Use --force to continue. 

Aborted due to warnings. 

Полная установка: https://github.com/markusfalk/test-travis

Test Run: https://travis-ci.org/markusfalk/test-travis

Спасибо за любую помощь :)

+0

Является ли мостовые проблема? Что можно сделать по этому поводу? http://stackoverflow.com/a/18433173/2538388 Но я действительно загружаю Qunit в HTML, а не через requireJS – Markus

+0

Я только что узнал, что использование [email protected] заставит эту настройку работать. Возможно, это связано с обновлением, которое они сделали: v0.6.0 Добавьте параметр noGlobals, перенаправленный в QUnit. Сообщите правильный код выхода, чтобы хрюкать на основе сбоев. Добавьте поддержку для AMD. – Markus

+0

Я переработал настройку на то, что предложил Йорн Зафферер (https://github.com/markusfalk/test-travis/tree/20150411_falk_require-qunit-as-amd/qunit), но он все еще не работает (https: // travis -ci.org/markusfalk/test-travis/builds/58909816) – Markus

ответ

4

С помощью Jörn Я придумал рабочую настройку. Trick - настроить requireJS до загрузки QUnit (переместить requireJS config в config.js и загрузить его сначала).

Требования:

  • хрюкать-вно-QUnit v0.7.0
  • QUnit v1.18.0

HTML набор тестов:

<!doctype html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>QUnit Tests Suite: asdf</title> 
    <link rel="stylesheet" href="../components/libs/qunit/qunit/qunit.css"> 
    </head> 
    <body> 

    <div id="qunit"></div> 
    <div id="qunit-fixture"></div> 

    <script src="config.js"></script> 
    <script data-main="unit" src="../components/libs/requirejs/require.js"></script> 

    </body> 
</html> 

конфигурации.JS

var requirejs = { 
    baseUrl: "../", 
    paths: { 
    //{{app}} 
    'foo': 'components/app/foo/foo', 
    'test-foo': 'components/app/foo/test-foo', 

    //{{libs}} 
    'unit': 'qunit/unit', 
    'qunit': 'components/libs/qunit/qunit/qunit', 
    'jquery.exists': 'libs/jquery.exists/jquery.exists', 
    'jquery': 'components/libs/jquery/dist/jquery.min' 
    }, 
    'shim': { 
    'jquery.exists': ['jquery'] 
    } 
}; 

unit.js

require([ 
    'qunit', 
    'test-foo' 
], 
function(qunit, TestFoo) { 
    TestFoo(); 
    qunit.start(); 
}); 

тест-foo.js:

define(['jquery', 'qunit', 'foo'], function($, qunit, Foo) { 
    'use strict'; 
    return function() { 
    qunit.module("Foo"); 
    qunit.test("Foo Test", function() { 
     equal(Foo.saySomething(), "Hello", "returns 'Hello'"); 
    }); 
    }; 
}); 

И, наконец, модуль я хочу тест:

define(['jquery'], function($) { 
    'use strict'; 
    var Foo = { 
    saySomething: function() { 
     return "Hello"; 
    } 
    }; 
    return { 
    saySomething: Foo.saySomething 
    }; 
}); 
0

Извинения заранее, если я заявив очевидное, но у вас установлен PhantomJS? Я не вижу его в файле packages.json. Вы можете установить его с помощью npm install phantomjs --save-dev в свой корень проекта. Сохранить-dev добавит его в ваш пакет.json, поэтому при запуске npm install он будет автоматически установлен.

+0

У меня установлен [email protected], который включает в себя phantomjs – Markus

1

Вы пытались запустить хрюканье с флагами -v и/или -d, чтобы получить более подробный вывод? Я заметил, что что-то пропустило в отношении PhantomJS в вашей сборке travis-ci.

Writing location.js file

PhantomJS is already installed at /usr/local/phantomjs/bin/phantomjs.

npm WARN excluding symbolic link lib/socket.io-client.js -> io.js

Если это зависит от io.js и ссылки там нет, это не удастся.

ОБНОВЛЕНИЕ: Я нашел проблему, используя подробный вывод. Из-за проблемы с именем файла ваш тест 404.

["phantomjs","onResourceReceived",{"contentType":"text/html; charset=utf-8","headers":[{"name":"X-Content-Type-Options","value":"nosniff"},{"name":"Content-Type","value":"text/html; charset=utf-8"},{"name":"Content-Length","value":"43"},{"name":"Date","value":"Fri, 10 Apr 2015 06:45:47 GMT"},{"name":"Connection","value":"keep-alive"}],"id":6,"redirectURL":null,"stage":"end","status":404,"statusText":"Not Found","time":"2015-04-10T06:45:47.747Z","url":" http://localhost:10000/components/app/foo/test-Foo.js "}]

Вы пытаетесь использовать файл test-Foo.js. Файл называется test-foo.js в вашем репозитории. Изменение корпуса должно исправить тест.

+0

Я добавил -vd в сборку travis, но на самом деле не имеет большого смысла это – Markus

+0

Я нашел ответ. Обновлен мой ответ, чтобы отразить то, что я нашел в подробном выпуске. – voldemortensen

+0

Спасибо за ваши усилия, но это не проблема. Я исправил 404, но все равно получаю тот же результат. – Markus