简体   繁体   中英

How to pass variables into cy.request for graphql/apollo without string interpolation

Currently, the below works but I know that it is bad practice and I don't want to run into an issue in the future as a result of this implementation.

export const loginQuery = ({ email, password }) => `
  mutation login {
    login(email: "${email}", password: "${password}") {
      authToken
    }
  }
`;

export default ({ url, method, userPath }) => {
  cy.fixture(userPath).then(res => {
    const query = loginQuery(res);
    cy.request({
      method,
      url,
      headers: { 'Content-Type': 'application/json' },
      body: { query },
      failOnStatusCode: false
    });
  });
};

How can I pass in variables normally instead of manually do it with string interpolation?

The reason I am writing it this way is because I cannot use react-apollo / graphql-tag . I have tried but graphql and react-apollo need to be wrapped in a component which does not apply in this cypress context.

NOTE: The above implementation does not work for objects/arrays. I would need to manually pass in the specific keys within a written out object in the mutation instead of just a variable to represent the entire object. This is obviously an issue.

The solution was much easier than anticipated. Unfortunately, I didn't see any example of this online but it works great.

export const loginQuery = `
  mutation login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      authToken
    }
  }
`;

export default ({ url, method, userPath }) => {
  cy.fixture(userPath).then(res => {
    cy.request({
      method,
      url,
      headers: { 'Content-Type': 'application/json' },
      body: { query: loginQuery, variables: res },
      failOnStatusCode: false
    });
  });
};

I had no idea I could just declare variables in the body and they would pass in without issue if I structured the query/mutation as I would normally.

The closest to my successful solution was this gist https://gist.github.com/yusinto/30bba51b6f903c1b67e0383f4a288269 . However, the gist still used string interpolation. Looks like he could simplify his gist by just setting variables.

This gist was found with @xadm 's suggested search string SO for mutations using fetch/curl/etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM