是否可以通过 Cypress 更新 React 上下文?

ell*_*kie 7 security reactjs cypress react-context

我使用 Cypress 进行集成测试(不适用于单元测试/组件测试),并使用具有身份验证逻辑的应用程序,具体取决于应用程序状态中安全令牌的存在 - 在使用的​​上下文之一(使用库创建)中react-tracked。没有它 - 就不可能与应用程序交互。据我所知,Cypress 不适合测试远程身份验证过程(例如通过 Azure AD),这就是为什么我需要在每次测试开始时通过将安全令牌注入来“预身份验证”应用程序上下文。我看到了如何直接访问 Redux 存储的示例:

\n
const store = createStore(reducer)\n\nrender(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n  document.getElementById(\'root\')\n)\n\n// expose store when run in Cypress\nif (window.Cypress) {\n  window.store = store\n}\n
Run Code Online (Sandbox Code Playgroud)\n

https://www.cypress.io/blog/2018/11/14/testing-redux-store/ \xe2\x80\x94 实际上我不太确定是否可以更新商店)

\n

我找不到类似的反应上下文解决方案。将令牌存储在 cookie 或本地存储中似乎风险太大。更改测试框架(Playwright 似乎是我们的一个不错的候选人)将是一件痛苦的事情。另一种选择是在应用程序中创建一个特殊的隐藏输入,以输入令牌 \xe2\x80\x94 但没有更好的方法吗?

\n

小智 -1

Cypress.Commands.add("token", () => {
  let access_token = "";
  cy.request({
    method: "POST",
    url: "/auth/realms/cmem/protocol/openid-connect/token",
    form: true,
    body: {
      client_id: Cypress.env("service_account_client_id"),
      client_secret: Cypress.env("service_account_client_secret"),
      grant_type: Cypress.env("service_account_grant_type"),
    },
  }).then((response) => {
    access_token = response.body.access_token;
    window.localStorage.setItem("ACCESS_TOKEN", access_token);
  });
});

function getAccessToken() {
  return window.localStorage.getItem("ACCESS_TOKEN");
}
Cypress.Commands.add("dropAllGraphs", () => {
  cy.request({
    method: "POST",
    url: "https:google.com",
    headers: { authorization: "Bearer " + getAccessToken() },
    failOnStatusCode: false,
  }).then((response) => {
    const status = response.status;
    if (status == 401) {
      cy.token();
      cy.dropAllGraphs();
    } else if (status == 503) {
      cy.dropAllGraphs();
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

我认为这对你有用