gpt4 book ai didi

javascript - Vue 模板中的函数调用测试仅在使用括号调用函数时通过

转载 作者:行者123 更新时间:2023-12-04 12:24:01 28 4
gpt4 key购买 nike

我正在使用带有 Jest (v24.9) 和 Vue-Test-Utils (v1.03) 的 Vue v2.6。
为了模拟一个方法,我看到了两种不同的语法,

wrapper.vm.updateCart = jest.fn();

wrapper.setMethods({ updateCart: jest.fn() });
但第一个没有记录,而第二个已弃用(参见 docs )。
问题是,对于这两种方法,使测试通过的唯一方法是在模板中调用带有括号的方法,这很奇怪,因为我读过的所有文档都以某种方式鼓励在模板中使用不带括号的方法.
所以这个测试:
test('Click on .btn calls the right function', () => {
const wrapper = shallowMount(Modal, {
propsData: {
validate: jest.fn(),
},
});
wrapper.setMethods({ updateCart: jest.fn() });
const $btn = wrapper.find('.btn');
$btn.trigger('click');
expect(wrapper.vm.updateCart).toHaveBeenCalled();
});
只有当我用括号调用方法时才会通过:
<button class="btn" @click="updateCart()">
{{ dictionary('remove') }}
</button>
但否则会失败(例如,使用 @click="updateCart" )。
测试模板中的事件是否正在调用函数的正确语法是什么?
以及为什么文档中的弃用警告( herehere )定​​义了 setMethod api作为反模式?
也许只测试模板中的事件触发函数是错误的,因为框架(Vue)应该已经保证了这种行为,而我们应该只专注于测试函数本身?
编辑 07/02/2020
我也尝试了不同的语法:
const spy = jest.spyOn(wrapper.vm, 'updateCart');
const $btn = wrapper.find('.btn');
$btn.trigger('click');
expect(spy).toHaveBeenCalled();
防止覆盖方法并替换对 setMethods 的调用,但仍然只有在使用括号调用函数时才能通过测试。

最佳答案

两个@click="updateCart"@click="updateCart()"支持语法变化,这令人困惑,因为 Vue DSL 允许在 v-on 中提供表达式.前者使用updateCart方法作为事件处理程序,而后者根据组件实例评估表达式并且不限于方法。@click="updateCart()"出于一致性原因,更可取,因为表达式通常在 Vue 模板中使用,@click="notAFunction"静默失败,而 @click="notAFunction()"引发错误。这也允许通过以下方式对其进行监视:

jest.spyOn(wrapper.vm, 'updateCart');
否则,该方法需要在组件实例化之前进行监视:
jest.spyOn(Modal.methods, 'updateCart');
const wrapper = shallowMount(Modal);
弃用 setMethod已解释:

There's no clear path to replace setMethods, because it really dependson your previous usage. It easily leads to flaky tests that rely onimplementation details, which is discouraged .

...

To stub a complex method extract it from the component and test it inisolation. To assert that a method is called, use your test runner tospy on it.


关于测试实现的担忧是主观的,因为这通常不是一件坏事。这取决于提取是否实用的情况,因为一个函数需要被提取到另一个模块才能被窥探。
至于 updateCart ,模拟更新汽车的底层 API 可能就足够了,而不是方法本身。
使用 stub 方法测试点击事件仍然可能有用,或者至少监视真实方法。以这种方式测试的是模板,而不仅仅是框架的行为。没有 spy ,不知道测试是否因为 btn 而失败或 updateCart .

关于javascript - Vue 模板中的函数调用测试仅在使用括号调用函数时通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62696939/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com