Skip to content

Instantly share code, notes, and snippets.

@epreston
Created April 28, 2023 18:44
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/ffdb6a49a5cc3f308d57a01812577665 to your computer and use it in GitHub Desktop.
Save epreston/ffdb6a49a5cc3f308d57a01812577665 to your computer and use it in GitHub Desktop.
vitest - generic test structures and examples
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
// ---------------------------------------------------------
// template unit test functions
// ---------------------------------------------------------
const isFn = (a) => typeof a === 'function';
const isString = (a) => typeof a === 'string';
const isNumber = (a) => typeof a === 'number';
// ---------------------------------------------------------
const DataObject = {
foo: 'bar',
baz: 'qux',
};
class SomeClass {
constructor() {
this.foo = 'bar';
}
baz() {
return 'qux';
}
}
function exposedFunction() {
return {};
}
const exposedObject = {
foo: 'bar',
baz() {
return 'qux';
},
};
// ---------------------------------------------------------
it('should expose an object', () => {
expect(exposedObject).toBeDefined();
expect(exposedObject).toBeInstanceOf(Object);
});
it('should expose a function', () => {
expect(exposedFunction).toBeDefined();
expect(exposedFunction).toBeInstanceOf(Function);
});
it('should return an object', () => {
const instance = exposedFunction();
expect(instance).toBeDefined();
expect(instance).toBeInstanceOf(Object);
});
it('has the expected properties', () => {
expect(exposedObject).toHaveProperty('foo');
expect(exposedObject.foo).toBe('bar');
});
it('should have a method baz()', () => {
// exposedObject.baz();
expect(exposedObject.baz).toBeDefined();
});
// ---------------------------------------------------------
let instance;
beforeAll(() => {
instance = new SomeClass();
});
// beforeEach(() => {
// instance = new SomeClass();
// });
it('can be instantiated', () => {
expect(instance).toBeDefined();
expect(instance).toBeInstanceOf(Object);
});
it('should be an instanceof SomeClass', () => {
expect(instance).toBeInstanceOf(SomeClass);
});
it('extends from SomeClass', () => {
expect(instance).toBeInstanceOf(SomeClass);
});
it('should have a method baz()', () => {
// instance.baz();
expect(instance.baz).toBeDefined();
});
// ---------------------------------------------------------
it('loads the test object correctly', () => {
expect(DataObject).toMatchSnapshot();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment