javascript - 如何在每个测试中以不同方式模拟用户模块?
问题描述
我的 Vue 组件有以下单元测试:
import { shallowMount } from '@vue/test-utils';
import OrganizationChildren from './OrganizationChildren.vue';
describe('OrganizationChildren', () => {
beforeEach(() => {
jest.resetModules();
});
it('passes', () => {
jest.doMock('@/adonis-api', () => {
return {
organization: {
family(id) {
return {
descendants: [],
};
},
},
};
});
const wrapper = shallowMount(OrganizationChildren, {
propsData: {
org: {
id: 1,
},
},
});
});
});
而在 Vue 组件中,它确实是import { organization } from '@/adonis-api';
. 我暂时只是 console.logging 导入的organization
对象,以确保它是正确的。但我可以看到它没有使用我指定的模拟版本。我究竟做错了什么?family
我的目标是在每个块中以不同的方式模拟该方法,it()
以测试如果descendants
为空、是否包含 5 个项目、100 个项目等会发生什么。
解决方案
解决了!我有几个问题,事实证明:
- 没有正确嘲笑
@/adonis-api
。我应该提到它只模拟顶层的东西,所以我不得不使用工厂函数jest.mock
(见下文)。 - 我需要一个
await flushPromises()
允许模板在其created()
方法评估我的模拟函数并将结果存储在this.children
.
全面测试:
import { shallowMount, config } from '@vue/test-utils';
import flushPromises from 'flush-promises';
import OrganizationChildren from './OrganizationChildren.vue';
import { organization } from '@/adonis-api';
jest.mock('@/adonis-api', () => ({
organization: {
family: jest.fn(),
},
}));
describe('OrganizationChildren', () => {
config.stubs = {
'el-tag': true,
};
it('shows nothing when there are no children', async () => {
organization.family.mockResolvedValueOnce({
descendants: [],
});
const wrapper = shallowMount(OrganizationChildren, {
propsData: {
org: {
id: 1,
},
},
});
await flushPromises();
const h4 = wrapper.find('h4');
expect(h4.exists()).toBe(false);
});
it('shows children when provided', async () => {
organization.family.mockResolvedValueOnce({
descendants: [{ name: 'One' }, { name: 'Two' }],
});
const wrapper = shallowMount(OrganizationChildren, {
propsData: {
org: {
id: 1,
},
},
});
await flushPromises();
const h4 = wrapper.find('h4');
const list = wrapper.findAll('el-tag-stub');
expect(h4.exists()).toBe(true);
expect(list.length).toBe(2);
expect(list.at(0).text()).toBe('One');
expect(list.at(1).text()).toBe('Two');
});
});
推荐阅读
- file - VBS 通过发送到菜单重命名文件
- javascript - Chartjs X 轴标签不会显示
- dynamics-ax-2012-r3 - DMF 和高级会计结构
- r - 如何在 R 中找到分类算法的执行时间?
- css - Flexbox 没有按预期工作 - 项目越来越小
- git - 远程 ssh 密钥身份验证的权限错误:git 附件获取文件
- excel - 如何在 Excel VBA 工作表函数中添加多个 SUMIFS
- android - 在 android 设备上获取离线 GPS 坐标
- c# - 创建流利的api问题
- spring - @Transactional 方法中的@Transactional 方法调用(都具有默认传播)