如何使用 Cypress 通过 next-auth 在 Next.js 中存根 useSession 和 getSession

Tru*_*ufa 5 stub sinon reactjs next.js cypress

我正在尝试使用 Cypress 对前端和后端调用进行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`)
Run Code Online (Sandbox Code Playgroud)

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

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

Séb*_*OUR 0

你需要使用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)
  })
})

Run Code Online (Sandbox Code Playgroud)

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