5

我们在使用 casper.js 进行功能测试时遇到了一点问题。

我们两次请求相同的资源,首先使用 GET,然后使用 POST 方法。现在在等待第二个资源(POST)时,它匹配第一个资源并直接转到“then”函数。

我们希望能够在“test”函数中检查 HTTP 方法,这样我们就可以正确识别资源。现在我们使用状态码(res.status),但这并不能完全解决我们的问题,我们真的需要http方法。

// create new email
this.click(xPath('//div[@id="tab-content"]//a[@class="button create"]'));

// GET
this.waitForResource('/some/resource', 
    function then() {
        this.test.assertExists(xPath('//form[@id="email_edit_form"]'), 'Email edit form is there');

        this.fill('form#email_edit_form', {
            'email_entity[email]': 'test.bruce@im.com',
            'email_entity[isMain]': 1
        }, true);

        // POST
        this.waitForResource(
            function test(res) {
                return res.url.search('/some/resource') !== -1 && res.status === 201;
            },
            function then() {
                this.test.assert(true, 'Email creation worked.');
            },
            function timeout() {
                this.test.fail('Email creation did not work.');
            }
        );
    },
    function timeout() {
        this.test.fail('Email adress creation form has not been loaded');
    });

或者也许有更好的方法来测试这种情况?尽管由于这是一项功能测试,我们需要将所有这些步骤保留在一个测试中。

4

2 回答 2

1

res传递给函数的参数test有一个 ID。我创建了一个助手来测试这个 ID 并将其列入黑名单,因此相同的资源不会被第二次接受。

var blackListedResourceIds = [],
    testUniqueResource = function (resourceUrl, statusCode) {
        return function (res) {
            // check if resource was already loaded
            var resourceFound = res.url.search(resourceUrl) !== -1;

            // check statuscode
            if (statusCode !== undefined) {
                resourceFound = resourceFound && res.status === statusCode;
            }

            // check blacklisting
            if (!resourceFound || blackListedResourceIds[res.id] !== undefined) {
                return false;
            } else {
                blackListedResourceIds[res.id] = true;
                return true;
            }
        };
    };
于 2012-11-09T08:44:44.883 回答
1

You can try to alter the form action url to add some query string, therefore generating a new resource appended to the stack. Could be done this way:

casper.thenEvaluate(function() {
    var form = __utils__.findOne('#email_edit_form');
    form.setAttribute('action', form.getAttribute('action') + '?plop');
});

That's a hack though, and functional testing should never be achieved that way. Let's hope more information will be added to the response objects in the future.

于 2012-11-10T07:40:45.663 回答