You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Enzyme模拟含API调用的点击事件失效问题求助

问题分析

你现在遇到了两个核心问题:

  1. 测试用例里的expect(true).toBe(true)是完全无效的断言——不管实际逻辑对错,这条断言都会通过,导致你根本没法验证功能是否正常工作。
  2. 异步操作没有被正确处理:addToFavourites是异步函数,但测试中没有等待它执行完成,导致POST请求还没发送到服务器、console.log还没执行,测试就已经结束了。另外,测试环境中你没模拟API请求,真实请求可能被框架拦截或者因为环境问题无法抵达服务器。
解决方案

我们一步步来修复这些问题:

1. 替换无效断言,聚焦真实逻辑

把毫无意义的expect(true).toBe(true)换掉,改成验证组件是否正确触发了目标函数、参数是否符合预期。

2. 模拟依赖与API请求

用Jest的jest.mock模拟addToFavourites、post请求以及通知类函数,避免真实API调用和副作用,让测试只关注组件的行为逻辑。

3. 处理异步操作

因为addToFavourites是async函数,点击按钮后的操作是异步的,测试必须等待这个异步流程完成才能进行断言,我们用async/await来实现这一点。


具体代码修改

测试文件调整

// 替换成你的工具函数实际路径
jest.mock('../path/to/your/utils', () => ({
  addToFavourites: jest.fn().mockResolvedValue({ 
    data: { success: true, mssg: 'Added to favourites' } 
  }),
  insta_notify: jest.fn(),
  Notify: jest.fn()
}));

import { addToFavourites, insta_notify, Notify } from '../path/to/your/utils';
import { mount, create } from 'enzyme';
import AddToFavourites from './Add-to-favourites';
import SecondaryButton from './SecondaryButton';

describe('AddToFavourites Component', () => {
  const comp = (
    <AddToFavourites user={7} username='ghalib' />
  )
  
  it('should match snapshot', () => {
    const tree = create(comp).toJSON()
    expect(tree).toMatchSnapshot()
  })
  
  it('should trigger addToFavourites and related logic when button is clicked', async () => {
    const wrapper = mount(comp)
    
    // 用await等待异步操作完成
    await wrapper.find(SecondaryButton).simulate(
      'click',
      { preventDefault() {} }
    )
    
    // 验证函数调用与参数是否正确
    expect(addToFavourites).toHaveBeenCalledWith(7);
    expect(insta_notify).toHaveBeenCalledWith({ to: 7, type: 'favourites' });
    expect(Notify).toHaveBeenCalledWith({ value: 'Added to favourites' });
  })
})

组件函数优化

把组件内的add函数改成async,确保异步操作被正确等待:

const AddToFavourites = ({ user, username }) => {
  // 改为async函数
  const add = async e => {
    e.preventDefault()
    await addToFavourites(user) // 等待异步请求完成
    new d('.af_btn').blur()
  }
  return (
    <div>
      <div className='recomm_teaser'>
        <span>Wanna add {username} to your favourites list.</span>
        <SecondaryButton label='Add' onClick={add} />
      </div>
    </div>
  )
}

工具函数添加错误处理

给addToFavourites加上try/catch,避免未捕获的Promise错误:

export const addToFavourites = async user => {
  try {
    const { data: { success, mssg } } = await post('/api/add-to-favourites', { user })
    if (success) {
      insta_notify({ to: user, type: 'favourites' })
    }
    console.log('Test debugging') // 现在会正常执行了
    Notify({ value: mssg })
  } catch (error) {
    console.error('Failed to add to favourites:', error)
    Notify({ value: 'Failed to add to favourites' })
  }
}
为什么原来的console.log没输出?

因为addToFavourites是async函数,它返回的是一个Promise。之前的测试没有等待这个Promise完成就结束了,所以Promise还没resolve,console.log就没机会执行。当你去掉POST请求后,函数变成同步的,console.log就会立即输出了。

内容的提问来源于stack exchange,提问作者Faiyaz Shaikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:40