Skip to content

Instantly share code, notes, and snippets.

@epreston
Last active April 28, 2023 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epreston/2d948e03feb816c084f85471f0db9d54 to your computer and use it in GitHub Desktop.
Save epreston/2d948e03feb816c084f85471f0db9d54 to your computer and use it in GitHub Desktop.
vitest - vue test file structure example
// @vitest-environment jsdom
import { config, mount, shallowMount } from '@vue/test-utils';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
// ---------------------------------------------------------
// Imports used by options API or compiled component
import {
createBlock,
createElementBlock,
normalizeClass,
normalizeStyle,
openBlock,
resolveComponent,
unref,
} from 'vue';
// ---------------------------------------------------------
// We dont mock vue or other npm dependencies in most cases
// vi.mock('vue');
vi.mock('../../src/app.js');
// ---------------------------------------------------------
// the component being tested
import { Component } from '../../src/vue/Component.js';
// global component requirements
import { globalComponent } from '../../src/vue/globalComponent.js';
// ---------------------------------------------------------
config.global.components = {
SomeComponent: globalComponent,
};
// ---------------------------------------------------------
describe('Component', () => {
it('should expose an object', () => {
expect(Component).toBeDefined();
expect(Component).toBeInstanceOf(Object);
});
it('has the expected properties', () => {
const wrapper = mount(Component, {
props: {
key: 1,
color: 'white',
class: 'button-content',
},
});
// console.log(wrapper.vm);
expect(wrapper.vm.color).toBeDefined();
expect(wrapper.vm.color).toBe('white');
wrapper.unmount();
});
it('can be clicked', async () => {
const wrapper = mount(Component, {
props: {
key: 1,
color: 'white',
class: 'button-content',
},
});
await wrapper.trigger('click');
// await wrapper.find('button').trigger('click');
// expect(something).toHaveBeenCalled();
wrapper.unmount();
});
it('renders correctly', () => {
const wrapper = mount(Component, {
props: {
key: 1,
color: 'white',
class: 'button-content',
},
});
// console.log(wrapper.html());
// console.log(wrapper.text()); // blank line if empty
// console.log(wrapper.element);
expect(wrapper.attributes('class')).toContain('button-content');
// expect(wrapper.element).toMatchSnapshot();
wrapper.unmount();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment