首页 > 解决方案 > 如何在每个测试中以不同方式模拟用户模块?

问题描述

我的 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 个项目等会发生什么。

标签: javascriptvue.jsjestjsvue-test-utils

解决方案


解决了!我有几个问题,事实证明:

  1. 没有正确嘲笑@/adonis-api。我应该提到它只模拟顶层的东西,所以我不得不使用工厂函数jest.mock(见下文)。
  2. 我需要一个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');
  });
});

推荐阅读