I am doing a “Sign In GraphQL” operation that takes some time using an Apollo Client, and I am trying to prevent the Asynchronous Event Driven nature of JavaScript from executing any API operations until I get my authentication token and so I can put it in my header for my next API request. I can't figure out a way around this tried callbacks, promises, chained promises and using Observables. I get my token promise fulfilled after my test has completed.
BBD Test: Given user signs in to hackernews-node api When user executes a "links" query Then the following links are returned: |id |url |description | |1 |www.graphqlconf.org |An awesome GraphQL conference |
// 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
My event log shows: 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"} info: WHEN: Query string - query {feed {id url description}} {"timestamp":"2021-04-18 09:54:00"} info: THEN: Read Expected Links from test Scenario {"timestamp":"2021-04-18 09:54:00"} error: THEN: query issues due to: Assignment to constant variable. {"timestamp":"2021-04-18 09:54:00"} info: JWT Token is : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImlhdCI6MTYxODc1NDA0MH0.dKCFH7XreKVrU7U-LFi4qvabo4D8IhpqoOc3sb10DVo {"timestamp":"2021-04-18 09:54:00"}