为什么 Jest spyOn() 只通过了其中一个测试,而另一个却失败了?

Why is Jest spyOn() only passing in one of these tests, but failing in the other?

我有一个 vue 子组件:

    <NavbarSnap
      title="Select Recipient"
      data-testid="navbarsnap"
      v-on:change-screen-handler="onHandleChangeScreen('SnapRecepient')"
      :hasSearch="true"
      :hasInvite="true"
      :groupName="getSelectedChannel.CNM"
      v-on:search-input="handleSearchInputChange"
    />

该组件有两个 v-on 指令。

我有两个几乎相同的测试。但是第一个通过,第二个失败:

  it("NavBarSnap change screen", async () => {
    const wrapper = factory();
    let spy = jest.spyOn(wrapper.vm, "onHandleChangeScreen");

    let element = wrapper.find("[data-testid='navbarsnap']");

    expect(element.exists()).toBeTruthy();
    element.vm.$emit("change-screen-handler");
    await wrapper.vm.$nextTick();

    expect(spy).toHaveBeenCalled();
  });

  it("NavBarSnap search input", async () => {
    const wrapper = factory();
    let spy = jest.spyOn(wrapper.vm, "handleSearchInputChange");

    let element = wrapper.find("[data-testid='navbarsnap']");

    expect(element.exists()).toBeTruthy();
    element.vm.$emit("search-input");
    await wrapper.vm.$nextTick();

    expect(spy).toHaveBeenCalled();
    // THIS TEST FAILS
  });

测试失败,因为 jest.fn() 还没有被调用。

两个被监视的函数都在同一个套件中进行了测试并且工作正常(尽管这在这里无关紧要)。这两个测试都以相同的方式获取组件并以相同的方式从子组件发出。我不明白为什么一个测试通过,一个测试失败。

有什么想法吗?

区别在于事件处理程序的注册方式:

v-on:change-screen-handler="onHandleChangeScreen('SnapRecepient')"

v-on:search-input="handleSearchInputChange"

前者根据组件实例评估表达式,并且不限于方法。后者使用 handleSearchInputChange 方法作为事件处理程序,这需要在组件实例化之前监视它:

let spy = jest.spyOn(Component.methods, "handleSearchInputChange");
const wrapper = factory();
...

为了保持一致,应该是v-on:search-input="handleSearchInputChange()"。这允许监视类似于 onHandleChangeScreen:

的实例
let spy = jest.spyOn(wrapper.vm, "handleSearchInputChange");
...