也许不相关,但最终遇到了同样的问题。这篇文章和@mateonunez 的回答帮助我解决了我的问题,所以我将把解决方案留给未来的读者。
我正在使用 jest 来测试单击按钮时是否出现模式。
let openModalBtn = wrapper.find('button[id="openModal"]');
expect(openModalBtn.exists()).toBe(true); // OK
expect(openModalBtn.is("button")).toBe(true); // OK
await deleteBtn.trigger("click"); // BANG
导致:
[Vue warn]: Error in v-on handler (Promise/async): "TypeError: this.$refs.confirmDialogue[0].show is not a function"
问题是我使用的是shallowMount:
// not good
describe("some test", () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(MyComponent, {...});
});
在MyComponent 的某个时刻,它需要执行以下操作:
...
methods: {
openModal() {
await this.$refs.confirmDialogue[0].show();
...
},
因此this.$ref 以undefined 的身份出现。
改用mount:
// good
describe("some test", () => {
let wrapper;
beforeEach(() => {
wrapper = mount(MyComponent, {...});
});
允许我单击该按钮并在 wrapper.html() 中找到存根。