简体   繁体   English

如何在没有字符串插值的情况下将变量传递给 graphql/apollo 的 cy.request

[英]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 .我这样写的原因是因为我不能使用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.我已经尝试过,但graphqlreact-apollo需要包装在一个不适用于此 cypress 上下文的组件中。

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.我需要在突变中手动传递写出的 object 中的特定键,而不仅仅是一个变量来表示整个 object。这显然是一个问题。

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 .最接近我的成功解决方案的是这个要点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这个要点是在@xadm 的建议搜索字符串SO for mutations using fetch/curl/etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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