在每个测试中如何以不同的方式模拟用户模块?

时间:2019-07-18 18:18:38

标签: javascript vue.js jestjs vue-test-utils

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

1 个答案:

答案 0 :(得分:0)

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

  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');
  });
});