首页 > 解决方案 > 在 Cucumber.js 测试中设置逻辑以在测试继续之前等待 json 令牌

问题描述

我正在使用 Apollo 客户端执行“登录 GraphQL”操作,该操作需要一些时间,并且我试图阻止 JavaScript 的异步事件驱动性质执行任何 API 操作,直到我获得身份验证令牌,因此我可以将其放入我的下一个 API 请求的标头。我想不出办法绕过这个尝试过的回调、承诺、链式承诺和使用 Observables。测试完成后,我实现了我的象征性承诺。

BBD 测试:给定用户登录到hackernews-node api 当用户执行“链接”查询然后返回以下链接:|id |url |description | |1 |www.graphqlconf.org |很棒的 GraphQL 会议 |

// Read in table data as expected list of Users and compare with returned list of users
Then('the following links are returned:', async function (dataTable) {  
    logger.info("THEN: Read Expected Links from test Scenario"); 
    var expectedData = dataTable.hashes();  // Table is an array of JS objects

    // Chained promises in hope of getting the following sequence in order login -> link query -> results validation 
    loginMutation(client, mut)
        .then(  (tkn) => { getQuery = (client, api_qry, tkn); } )
        .then((rtnData) => { assert(userDriver.ValidateQuery(expectedData, rtnData)); } )
        .catch( error => { logger.error(' THEN: query issues due to: ' + error.message); });
});

// Login mutation as a Promise
    function loginMutation(clnt, mut){
        return new Promise(
            (resolve, reject) =>{
                var tkn = userLogin(clnt, mut);
                if(typeof tkn !== 'undefined'){
                    resolve(tkn);     // fulfilled got token
                } else {
                    reject('');           // Got nothing
                }
            }
        );
    }

// Perform a login mutation
    function userLogin(clnt, mut){
        var jwt = '';
        clnt.mutate({
            mutation: gql`${mut}`
        }).then( (result) => {
            jwt = result.data.login.token;
            logger.info(`JWT Token is : ${jwt}`);
        });
        return jwt;
    }  // end login

我的事件日志显示: info: Connecting to API: http://localhost:4000 {"timestamp":"2021-04-18 09:54:00"} info: GIVEN: Setup Apollo Client and login query {"timestamp" :"2021-04-18 09:54:00"} 信息:WHEN:查询字符串 - 查询 {feed {id url description}} {"timestamp":"2021-04-18 09:54:00"} 信息: THEN:从测试场景中读取预期链接 {"timestamp":"2021-04-18 09:54:00"} 错误:THEN:查询问题由于:分配给常量变量。{"timestamp":"2021-04-18 09:54:00"} info: JWT Token is : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImlhdCI6MTYxODc1NDA0MH0.dKCFH7XreKVrU7U-LFi4qvabo4D8IhpqoOc3sb10DVo {"timestamp":"2021-04-18 09:54:00"}

标签: javascriptgraphqlcucumberjs

解决方案


推荐阅读