【问题标题】:How to use Cypress to stub useSession and getSession in Next.js with next-auth如何使用 Cypress 将 Next.js 中的 useSession 和 getSession 与 next-auth 存根
【发布时间】:2023-02-14 08:12:44
【问题描述】:

我试图用赛普拉斯存根分别对useSession()getSession()的前端和后端调用。

存根函数似乎不会替换函数或被调用:

我正在尝试这样做:

const client = require("next-auth/react")
....
....
cy.stub(client, "getSession").returns({
  user: {
    name: "xxx",
    email: "xxx",
    image: "xxx",
  },
  expires: "2022-07-08T09:49:47.602Z",
})
cy.stub(client, "useSession").returns({
  user: {
    name: "xxx",
    email: "xxx",
    image: "xxx",
  },
  expires: "2022-07-08T09:49:47.602Z",
})
cy.visit(`/draft/cl45ip2d600379as17epvu6ti`)

我试过用谷歌搜索它,但大多数人似乎为此使用 jest 而不是 cypress 并且似乎没有很多文档而且我不确定如何继续。

我不确定这是否相关,但是对 getSession 的调用是由客户端对 api 的 http 请求触发的。

【问题讨论】:

  • 你有没有让它工作?我刚开始使用 Cypress,我正在研究使用 Next.js 开始测试的最佳方式是通过已验证的用户设置。

标签: reactjs next.js cypress sinon stub


【解决方案1】:

你需要使用cy.stub(useSession, 'prototype').returns('my_value')

以下测试可以在执行时在我的 chrome 控制台中打印控制台警告:

import React from 'react'
import FormCreationConcession from './FormCreationConcession'
import TEST_TYPES from '@/Constants/tests-types'
import {useSession, SessionProvider} from 'next-auth/react'
import {testLocators} from '@/Constants/testLocators'

// https://medium.com/geekculture/component-testing-next-js-application-with-cypress-28fa311adda6
describe(`${TEST_TYPES.component.integration} <FormCreationConcession /> works correctly for professionnal site user`, () => {
  beforeEach(() => {
    // see: https://on.cypress.io/mounting-react
    cy.mount(
      <SessionProvider session={{}}>
        <FormCreationConcession />
      </SessionProvider>
    )

    cy.stub(useSession, 'prototype').returns(console.warn('testttt'))
  })

  it('findByTestId', () => {
    cy.findByTestId(testLocators.components.FormCreationConcession.title)
  })
})

阅读 https://docs.cypress.io/api/commands/stub,然后分析我如何操作一个函数,这是一种通过执行 // console.log('useSession : ', Object.getOwnPropertyDescriptors(useSession)) 的对象帮助我找到了答案。

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2021-10-10
    • 2021-10-26
    • 1970-01-01
    • 2020-10-29
    • 2022-07-24
    • 2021-08-06
    • 2022-11-25
    • 2021-02-11
    相关资源
    最近更新 更多