【问题标题】:@ok listener is not triggered on b-modal with jest-test-utils (vue-bootstrap)使用 jest-test-utils (vue-bootstrap) 在 b-modal 上未触发 @ok 侦听器
【发布时间】:2019-11-20 06:59:40
【问题描述】:

我正在使用带有 @ok="save" 钩子的 vue-bootstrap b-modal

mycomponent.vue 看起来像这样:

<template>
  <div>
    <b-button @click="add">open modal</b-button>
    <b-modal static lazy id="modal-detail" @ok="save">
      <b-form-input v-model="fooName"></b-form-input>
    </b-modal>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

import { RestClient } from "./RestClient";

@Component({ name: "fooController" })
export default class FooController extends Vue {
  public fooName = "";
  public add(): void {
    this.$root.$emit("bv::show::modal", "modal-detail");
  }
  public save(): void {
    console.log("in save method");
    RestClient.create(this.fooName);
  }
}
</script>

RestClient.ts 看起来像这样:

export class RestClient {
  static create(payload: string) {
    return payload;
  }
}

测试看起来像这样:

import { createLocalVue, mount } from "@vue/test-utils";
import BootstrapVue from "bootstrap-vue";
import MyComponent from "./mycomponent.vue";
import { RestClient } from "./RestClient";

jest.mock("./RestClient.ts", () => ({
  RestClient: {
    create: jest.fn(() => {
      return {};
      //   return Promise.resolve({});
    })
  }
}));

describe("component test", () => {
  const localVue = createLocalVue();
  localVue.use(BootstrapVue);

  it("should call the create method on the REST client when ok-ing the modal", (done) => {
    const wrapper = mount(MyComponent, {
      attachToDocument: true,
      localVue
    });
    expect(wrapper.isVueInstance()).toBe(true);

    // there is just one button: the open modal button
    wrapper.find("button").trigger("click");
    const modal = wrapper.find("#modal-detail");

    modal.vm.$emit("ok");

    return wrapper.vm.$nextTick().then(() => {
      expect(RestClient.create).toBeCalled();
      return wrapper.vm.$nextTick().then(done);
    });
 });
});

我直接在模式上发出ok 事件。 然后我正在查看要执行的保存方法中的 console.log 语句,在执行测试时我在终端中看不到。

因此,RestClient.create-方法没有被调用。 为什么?

【问题讨论】:

    标签: javascript typescript vue.js bootstrap-vue


    【解决方案1】:

    @ok 是自定义的 Vue 事件,而不是原生浏览器 DOM 事件。 .prevent 修饰符不适用于自定义 Vue 事件。

    【讨论】:

    • 删除.prevent 仍然不会触发save-方法
    • github.com/bootstrap-vue/bootstrap-vue/blob/dev/src/components/… ,我认为 @ok 事件在这种情况下是特定于 vue-bootstrap 的。
    • 是的,它是 BootstrapVue 的自定义 Vue 组件事件(我写了代码)
    • 那么我如何测试 modal.vm.$emit("ok") 是否实际调用了关联方法?
    • 如果使用JEST,则使用jest.fn()设置模拟保存功能,您仍然可以使用Vue测试工具找到确定按钮并单击它。注意模态使用转换,因此您需要await 以在安装模态后完成requestAnimationFrame,然后再搜索按钮并单击它。您可以在github.com/bootstrap-vue/bootstrap-vue/blob/dev/src/components/… 了解我们如何测试模态
    猜你喜欢
    • 2020-12-30
    • 2020-09-08
    • 2019-02-10
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    相关资源
    最近更新 更多