量角器:尝试返回值时未定义 [英] Protractor: Getting undefined while trying to return a value

查看:49
本文介绍了量角器:尝试返回值时未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个发送 GET 请求并返回响应的函数.

I have written a function which sends a GET request and returns the response.

this.generateToken = function() {
    var options = {
       uri: 'http://localhost:10000/token',
       method: 'GET',
       headers: {
         'Authorization': "YWRtaW46YWRtaW4="
       },
    };
    request(options, function (error, response, body) {
       var messageresponse = response.body.toString();
       console.log(messageresponse); //I am able to print the response
       return messageresponse;
    });
};

我可以在 request() 中打印 'messageresponse' 变量的值.
正在从我的一个测试中调用此函数:

I am able to print the value of 'messageresponse' variable inside request().
This function is being called from one of my test:

it('Post a GET request and generate a response', function () {
    var response = commonFunctionObj.generateToken();
    response.then(function(value){     //Getting below mentioned error on this line
       console.log(value);
    });
});

获取错误:TypeError:无法在调用函数中读取未定义的属性then".
有人可以帮忙吗?

Getting error: TypeError: Cannot read property 'then' of undefined in teh calling function.
Can someone please help?

推荐答案

您需要创建一个 promise 并解析一次以接收响应.看看下面的代码.

You need to create a promise and resolve it once to receive the response. Look at the below code.

this.generateToken = function() {
var deffered = protractor.promise.defer(); //create a promise
var options = {
   uri: 'http://localhost:10000/token',
   method: 'GET',
   headers: {
     'Authorization': "YWRtaW46YWRtaW4="
   },
};
  request(options, function (error, response, body) {
     var messageresponse = response.body.toString();
     console.log(messageresponse); 
     deffered.fulfill(messageresponse); //Instead of returning the response message, fulfill the promise that we created early.
  });

return deffered.promise; //return the created promise.
};

现在,您可以在任何测试中调用 generateToken() 方法,该方法将返回一个承诺,该承诺仅在从 API 调用收到响应时解析.

Now you can call the generateToken() method inside any of your test that will return a promise which is resolved only when the response is recieved from API call.

it('Post a GET request and generate a response', function () {
     var response = commonFunctionObj.generateToken(); 
     response.then(function(value){   
     console.log(value);
    });
});

这篇关于量角器:尝试返回值时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆