使用ViTest对Vue组件进行单元测试并模拟方法的方法指南
P粉445750942
P粉445750942 2023-08-29 00:23:20
[Vue.js讨论组]
<p>使用vitest来模拟方法,通过单元测试vue组件。</p> <p><em>MyComponent.vue</em></p> <pre class="brush:php;toolbar:false;">&lt;script setup&gt; import { ref } from &quot;vue&quot;; const isSelectAll = ref(true); const selectAllModel = ref(false); const onChange = () =&gt; { isSelectAll.value = true; selectAllModel.value = false; }; const onVisibleChange = () =&gt; { // do something than call onChange(); }; &lt;/script&gt;</pre> <p>我想通过模拟<code>onChange</code>来单元测试<code>onVisibleChange</code>方法,并检查<code>onChange</code>是否被调用。</p> <p><em>MyComponent.spec.js</em></p> <pre class="brush:php;toolbar:false;">import { mount } from 'vitest'; import { ref } from 'vue'; import MyComponent from './MyComponent.vue'; describe('MyComponent', () =&gt; { const wrapper = shallowMount(MyComponent); const spy = vi.spyOn(wrapper.vm, 'onChange'); wrapper.vm.onVisibleChange(); expect(spy).toHaveBeenCalled(); expect(wrapper.vm.onChange).toHaveBeenCalled(); // Both the expect gives error: AssertionError: expected &quot;onChange&quot; to be called at least once //Also tried const mock = vi.fn(); wrapper.vm.onChange = mock; wrapper.vm.onVisibleChange(); expect(mock).toHaveBeenCalled(); // AssertionError: expected &quot;spy&quot; to be called at least once expect(wrapper.vm.onChange).toHaveBeenCalled(); // TypeError: [Function onChange] is not a spy or a call to a spy! })</pre></p>
P粉445750942
P粉445750942

全部回复(1)
P粉311423594

测试方法并不是一个好主意。因为函数的名称可能会改变。

更好的方法是测试:

  1. 从组件中发出的事件。也许你的 onChange() 包含了事件的发出。这个发出应该被测试。
  2. 模板中的变化。例如,你的 onChange() 改变了模板。所以这些变化也应该被测试。
  3. 调用其他函数。例如,你有一些在项目中通用的函数。这些函数可以使用 spy.on 进行测试。
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号