对未导出的函数进行玩笑间谍 REACT

问题描述 投票:0回答:1

如何使用 JEST 监视编写在函数组件内的未导出函数?

const ProfilePage: NextPage<Props> = ({
const getUser = () => {
return {
 name: 'Joker',
}
}
return (
<Box>Hello world</Box>
)
)}

我想监视 getUser 函数,看看它是否返回

{name: 'Joker'}
。我尝试使用酶,但这对我不起作用,因为它不适用于 React 18 版本。

it('GetUserSpy', () => {
    jest.spyOn(ProfilePage.prototype,'getUser') // prototype is undefined because its a function component
  });
next.js jestjs ts-jest next
1个回答
0
投票

不幸的是你不能这样做。但是您可以简单地从组件中提取函数并将其导出。如果您在函数中不使用任何钩子,那应该不是问题。

另请注意,间谍活动的目的不是检查 returnValue。如果您想查看 getUser 函数返回什么,您可以简单地在测试中调用它并使用

expect(result).toBe({name: 'Joker'})
为此,您还需要导出该函数。如果你确实想监视,这应该可行:

export const getUser = () => ({
  name: 'Joker',
})

const ProfilePage: NextPage<Props> = ({
  const user = getUser()
  return (
    <Box>Hello world</Box>
  )
)}
import * as getUserModule from 'path/to/module';

describe('ProfilePage', () => {
  it ('should call getUserSpy', () => {
    //GIVEN
    const getUserSpy = jest.spyOn(getUserModule,'getUser') 
    //WHEN
    render(<ProfilePage />)
    //THEN
    expect(getUserSpy).toHaveBeenCalled();
  })
})

© www.soinside.com 2019 - 2024. All rights reserved.