Как проверить вызовы jquery и ajax с помощью JsTestDriver? - PullRequest
6 голосов
/ 16 июля 2011

У меня есть динамическая страница, созданная с помощью jQuery.Куски HTML загружаются из усов шаблонов.Эти шаблоны загружаются с URL-адреса, и я хотел бы провести модульное тестирование всей конструкции HTML:

Тест JsTestDriver:

AppTest = TestCase("AppTest")

AppTest.prototype.test = function() {
    var actualHtml = "";

    getHtml({ "title": "title", "header": "header", "text": "text", "authors": [ {"firstname": "firstname", "lastname": "lastname"} ] }, function(html) {
        actualHtml = html;
    });

    assertEquals("expected html", actualHtml);
};

И код:

function getHtml(json, resultFunc) {
   jQuery.ajax({
            url: "url/to/mustache/template",
            success: function(view) {
                    resultFunc(mergeArticleModelAndView(json, view));
            },
            error: function(jqXHR, textStatus, errorThrown) {
                    resultFunc(textStatus + " errorThrown: " + errorThrown);
            },
            dataType: 'text',
            async: false 
    });
}

Затем я запускаю тесты, и результат таков:

$ java -jar JsTestDriver-1.3.2.jar --port 9876 --browser /usr/bin/firefox --tests all
F
Total 1 tests (Passed: 0; Fails: 1; Errors: 0) (8,00 ms)
  Firefox 5.0 Linux: Run 1 tests (Passed: 0; Fails: 1; Errors 0) (8,00 ms)
    AppTest.test failed (8,00 ms): AssertError: expected "expected html" but was "error errorThrown: [Exception... \"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)\"  nsresult: \"0x80004005 (NS_ERROR_FAILURE)\"  location: \"JS frame :: http://localhost:9876/test/main/js/jquery.min.js :: <TOP_LEVEL> :: line 16\"  data: no]"
  ()@http://localhost:9876/test/test/js/app_test.js:25

Итак, был вызван обратный вызов ошибки, и я не понимаю, почему он разрывается с JsTestDriver, и код работает при вызове приложения.вручную с помощью браузера

Последнее, jsTestDriver.conf:

server: http://localhost:9876

load:
  - test/js/app_test.js
  - main/js/jquery.min.js
  - main/js/jquery.mustache.js
  - main/js/app.js

Спасибо за советы.В целом, какие платформы модульного тестирования вы используете для тестирования javascript и командной строки с помощью DOM и jQuery?

Ответы [ 4 ]

5 голосов
/ 31 января 2012

Альтернативой может быть получение JsTestDriver для обслуживания вашего шаблона и некоторых тестовых данных JSON.Приведенная ниже конфигурация позволяет вам помещать статические тестовые данные JSON (например, my_data.json) в шаблоны src / test / webapp / json и Mustache в src / main / webapp / templates.Вы можете изменить это так, чтобы он соответствовал макету вашего исходного кода, если это слишком Maven-y для ваших вкусов.

Обратите внимание, что JsTestDriver обслуживает ресурсы с / test / pre-pended к URI, указанному в атрибуте serve, поэтомуsrc / test / webapp / json / my_data.json на самом деле обслуживается с http: / /localhost:9876/test/src/test/webapp/json/my_data.json.

server: http://localhost:9876

serve:
- src/main/webapp/templates/*.html
- src/test/webapp/json/*.json

load:
- src/main/webapp/js/*.js
- src/main/webapp/js/libs/*.js

test:
- src/test/webapp/js/*.js

Затем вВ тестовом примере вы можете легко загрузить шаблон и данные JSON.

    testLoadTemplateAndData : function () {

        // Variables
        var onComplete, template, data, expected, actual, templateLoaded, dataLoaded;
        dataLoaded = false;
        templateLoaded = false;
        expected = "<h2>Your expected markup</h2>";

        // Completion action
        onComplete = function () {
            if (dataLoaded && templateLoaded) {

                // Render the template and data
                actual = Mustache.to_html(template, data);

                // Compare with expected
                assertEquals('Markup should match', expected, actual);

            }
        };

        // Load data with jQuery
        $.ajax({
            url : '/test/src/test/webapp/json/demo.json', 
            success : 
                function (result) {
                    data = result;
                    dataLoaded = true;
            },
            error : 
                function () {
                    fail("Data did not load.");
            },
            complete :
                function () {
                    onComplete();
                }
            }
        );

        // Load the template with jQuery
        $.get('/test/src/main/webapp/templates/demo.html',
            function(result) {
                template = result;
                templateLoaded = true;
            }
        )
        .error(function() { fail("Template did not load."); })
        .complete(function() {
            onComplete();
        });

    }

После завершения обоих обратных вызовов jQuery, Mustache должен проанализировать шаблон с данными JSON и отобразить ожидаемый результат.

4 голосов
/ 19 июля 2011

Я нашел способ сделать это: посмеяться над вызовами ajax. На http://tddjs.com/ есть пример для этого в главе 12, а репозиторий git находится здесь: http://tddjs.com/code/12-abstracting-browser-differences-ajax.git

Итак, тестовый код:

TestCase("AppTest", {
    setUp: function() {
        tddjs.isLocal = stubFn(true);
        var ajax = tddjs.ajax;
        this.xhr = Object.create(fakeXMLHttpRequest);
        this.xhr.send=function () {
            this.readyState = 4;
            this.onreadystatechange();
        };
        this.xhr.responseText="<expected data>";
        ajax.create = stubFn(this.xhr);
    },


   "test article html ok": function () {
        var actualHtml = "";

        getHtml({ "title": "title", "header": "header", "text": "text", "authors": [ {"firstname": "firstname", "lastname": "lastname"} ] }, function(html) {
            actualHtml = html;
        });

        assertEquals("<expected html>", actualHtml);
   }
});

И производственный код:

function getHtml(model, resultFunc) {
        tddjs.ajax.get("http://url/to/template", {
                success: function (xhr) {
                        resultFunc(mergeArticleModelAndView(model, xhr.responseText));
                }
        });
}

Прочитав код jQuery, я думаю, что можно смоделировать запрос jQuery ajax. Cf также jquery 1.5 mock ajax

3 голосов
/ 20 июля 2011

Да, можно сделать то же самое с jquery:

Тестовый код (только настройка тест одинакова):

TestCase("AppTest", {
    setUp: function() {
        this.xhr = Object.create(fakeXMLHttpRequest);
        this.xhr.send=function () {
            this.readyState = 4;
        };
        this.xhr.getAllResponseHeaders=stubFn({});
        this.xhr.responseText="<expected data>";
        jQuery.ajaxSettings.isLocal=stubFn(true);
        jQuery.ajaxSettings.xhr=stubFn(this.xhr);
    },
// same test method

И производственный код:

function getHtml(model, resultFunc) {
        $.get("/url/to/template", function(view) {
                resultFunc(mergeArticleModelAndView(model, view));
        });
}

Это решение, которое мы выбрали.

0 голосов
/ 28 января 2014

С sinon.js это еще проще:

TestCase("AppTest", {
setUp: function() {
    this.server = sinon.fakeServer.create();
},
tearDown: function() {
    this.server.restore();
},

"test article html ok": function () {
    this.server.respondWith("mustache template");
    this.server.respond();
    var actualHtml = "";

    getHtml({ "title": "title", "header": "header", "text": "text", "authors": [ {"firstname": "firstname", "lastname": "lastname"} ] }, function(html) {
        actualHtml = html;
    });

    assertEquals("<expected html>", actualHtml);
}
...