vuejs / test-utils

Vue Test Utils for Vue 3
https://test-utils.vuejs.org
MIT License
1.04k stars 245 forks source link

Bug: 使用 wrapper.trigger('click') 无法正常触发 el-radio #2508

Closed JZLeung closed 2 months ago

JZLeung commented 2 months ago

Describe the bug

在项目的组件中使用了 ElRadio 组件,需要进行测试。

在测试中:

const [radio1, radio2] = wrapper.findAll('.el-radio')
await radio2.trigger('click')
expect(radio2.classes()).toContain('is-checked') // AssertionError: expected [ 'el-radio' ] to include 'is-checked'

无法【点击】到 radio2,使测试出错

To Reproduce

Element Plus Playground

Expected behavior

测试正常通过

Related information:

"vue": "3.4.21", "element-plus": "2.6.0",

"vitest": "^1.5.2", "@vue/test-utils": "^2.4.5",

Additional context

在控制台中,可以通过 document.querySelector('.el-radio').click() 正常触发,但无法通过 dom.dispatchEvent() 触发,恰巧这是 @vue/test-utilswrapper.trigger 的实现原理。

cexbrayat commented 2 months ago

Hi @JZLeung

I don't speak chinese, so I can only guess what the issue is, and answer in english, sorry.

You probably need to use attachTo in that case:

describe('Radio group', () => {
  it('create', async () => {
    const wrapper = mount(RadioComponent, { attachTo: document.body })
    await nextTick()

    const [radio1, radio2] = wrapper.findAll('.el-radio')
    expect(radio1.classes()).toContain('is-checked')

    await radio2.trigger('click')
    expect(radio2.classes()).toContain('is-checked')
  })
})

I think this should solve your issue. If not, open a repro on Stackblitz, and I'll take a look.

JZLeung commented 2 weeks ago

Hi @JZLeung 嗨 @JZLeung

I don't speak chinese, so I can only guess what the issue is, and answer in english, sorry. 我不会说中文,所以我只能猜测问题是什么,然后用英语回答,对不起。

You probably need to use attachTo in that case: 在这种情况下,您可能需要使用 attachTo:

describe('Radio group', () => {
  it('create', async () => {
    const wrapper = mount(RadioComponent, { attachTo: document.body })
    await nextTick()

    const [radio1, radio2] = wrapper.findAll('.el-radio')
    expect(radio1.classes()).toContain('is-checked')

    await radio2.trigger('click')
    expect(radio2.classes()).toContain('is-checked')
  })
})

I think this should solve your issue. If not, open a repro on Stackblitz, and I'll take a look.我认为这应该可以解决您的问题。如果没有,请在 Stackblitz 上打开一个重现,我会看一下。

It works, it's so cool. Thanks a lot.