ts-mockgen
v0.0.14
Published
Generate mock objects from TypeScript types using the TypeScript AST (ts-morph).
Maintainers
Readme
ts-mockgen
ts-mockgen is a TypeScript utility that lets you create partial mock objects of complex types for unit testing.
It helps keep tests independent and focused by letting you specify only the fields that are relevant to a test case, while safely filling in the rest.
It easily integrates with testing frameworks like Vitest and Jest.
Example
Suppose you have the type:
type UserProfile = {
id: number;
name: string;
address: {
city: string;
zip: string;
};
preferences: {
theme: string;
notifications: boolean;
};
createdAt: Date;
};With the following function to test
function updateTheme(user: UserProfile, newTheme: string): UserProfile {
return {
...user
preferences: { theme: newTheme};
}
}You can use generateMock like this
import { generateMock } from 'ts-mockgen';
it('should update the user theme', () => {
const mockUser: UserProfile = generateMock("UserProfile", {
preferences: { theme: "light" },
});
const updatedMockUser = updateTheme(mockUser, 'dark');
expect(updatedMockUser.preferences.theme).toBe('dark');
});