如何在Protractor测试中进行直接服务器调用并验证返回的数据?

时间:2015-05-21 14:06:40

标签: angularjs node.js jasmine protractor

我的Angular应用程序有一个Protractor测试,它会注册一个新用户,登录到应用程序然后删除该帐户。我的应用目前在其用户界面中没有“删除帐户”功能。但是,它确实有一个删除用户的API。我有以下测试用于删除帐户。

var request = require('request');
...
describe('delete', function () {
    var jar, req;

    beforeEach(function () {
        jar = request.jar();
        req = request.defaults({
            jar: jar
        });
    });

    it('should delete account successfully', function () {
        req.post({
            json: true,
            url: constants.apiHostname() + '/api/v1/login/',
            form: {username: generatedEmail, password: password}
        }, function (error, message, body) {
            var userId = body.user.id;

            console.log("Deleting userId: " + userId);

            req.del(constants.apiHostname() + '/api/v1/users/' + userId, function (error, message, body) {
                console.log(message.statusCode);
            });
        });
    });
})

我希望能够对返回的数据设定期望值。我尝试在“var userId”行之后添加以下内容:

expect(userId).to.not.be(null);

当我这样做时,我得到一个错误,即没有当前规范:

/Users/mraible/dev/myapp/node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:792
        throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out');
              ^
Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out
    at Env.expect (/Users/mraible/dev/myapp/node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:792:15)
    at jasmineInterface.expect (/Users/mraible/dev/myapp/node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:2869:18)
    at global.expect (/Users/mraible/dev/myapp/node_modules/protractor/node_modules/jasminewd2/index.js:151:10)
    at Request._callback (/Users/mraible/dev/myapp/tests/e2e/account.js:116:17)

是否可以在Protractor测试中直接调用API并验证结果?

1 个答案:

答案 0 :(得分:2)

我徘徊,如果是因为他们正在进行请求的异步性质,可能会将“完成”传递给测试函数并在回调期望之后调用它?类似的东西:

it('should delete account successfully', function (done) {
        req.post({
            json: true,
            url: constants.apiHostname() + '/api/v1/login/',
            form: {username: generatedEmail, password: password}
        }, function (error, message, body) {
            var userId = body.user.id;
            expect(your expectation);
            done();
        });
    });

如果这不起作用,回调中body的输出是什么?