如何在邮递员的“预请求脚本”部分中运行GraphQL请求?

时间:2020-08-24 22:31:50

标签: api testing graphql postman

我想在实际请求运行之前运行查询,并从请求前响应中获取一个值并将其设置在集合变量中。 我在测试REST API时曾经执行以下操作时遇到问题。

这就是我试图做的

const getUserBeforeUpdate = {
  url: pm.environment.get("base-url"),
  method: 'POST',
  header: {
   'content-type': 'application/json',
   'Authorization': `Bearer ${pm.environment.get("token")}`},
  body: JSON.stringify({query: '{ user { profile {id} } }'})
};
 
 pm.sendRequest(getUserBeforeUpdate, function(err, response) {
    pm.expect(response.code).to.eql(200);
   
    // set collection variable from the response
 });

但是我收到一个控制台错误提示

There was an error in evaluating the Pre-request Script:  Error: Unexpected token u in JSON at position 0

在graphql中链接请求的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

我没有能力运行您的请求,但这行得通吗?

const getUserBeforeUpdate = {
    url: `${pm.environment.get("base-url")}`,
    method: 'POST',
    header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${pm.environment.get("token")}`},
    body: JSON.stringify({
        query: 'query { user { profile { id } } }'
    })
};
 
 pm.sendRequest(getUserBeforeUpdate, function(err, response) {
    pm.expect(response.code).to.eql(200);
    // set collection variable from the response
 });

答案 1 :(得分:0)

我能够通过将url值直接作为字符串更改为实际url来解决此问题。我不确定为什么无法从环境获取变量。

答案 2 :(得分:0)

集合变量可通过collectionVariables访问。这应该为您工作:

const getUserBeforeUpdate = {
  url: pm.collectionVariables.get("base-url"),
  method: 'POST',
  header: {
   'content-type': 'application/json',
   'Authorization': `Bearer ${pm.collectionVariables.get("token")}`},
  body: JSON.stringify({query: '{ user { profile {id} } }'})
};
 
 pm.sendRequest(getUserBeforeUpdate, function(err, response) {
    pm.expect(response.code).to.eql(200);
   
    // set collection variable from the response
 });