@ok侦听器未通过jest-test-utils(vue-bootstrap)在b-modal上触发

时间:2019-07-10 15:42:01

标签: javascript typescript vue.js bootstrap-vue

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

可以找到here(现在已经过时)的MEW。

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方法。 为什么?

1 个答案:

答案 0 :(得分:0)

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