DEV Community

Cover image for Simplify Your Mock Data Creation in Tests with @lifeiscontent/to-mocked
Aaron Reisman
Aaron Reisman

Posted on

Simplify Your Mock Data Creation in Tests with @lifeiscontent/to-mocked

Are you spending too much time constructing complex mock data for your tests? Do you often find yourself ensuring that the mock data accurately reflects the actual types, but feeling it's a tedious and error-prone process? That's where the @lifeiscontent/to-mocked package steps in.

toMocked is a TypeScript utility function designed specifically to streamline the creation of mocked data structures for testing. It was conceived to address the challenges that come with generating intricate mock data. Instead of manually building an entire object for testing, this function allows you to specify the object type and provide only the necessary data that's actually used in the test.

Consider a User type for instance:

type User = {
  name: string;
  age: number;
  address: {
    city: string;
    country: string;
  };
};
Enter fullscreen mode Exit fullscreen mode

You can easily create a mocked user with toMocked:

let user = toMocked<User>({
  name: "Alice",
  age: 30,
  address: {
    city: "CityX",
  },
});

// "Alice"
console.log(user.name);
 // "CityX"
console.log(user.address.city);
 // Throws Error: Property "country" does not exist on...
console.log(user.address.country);
Enter fullscreen mode Exit fullscreen mode

The added benefit of using toMocked is the immediate feedback it provides when application code changes and tests break. It shows how the expectations have changed, making it significantly easier to maintain and update your test suite. Especially when you're using testing frameworks like Vitest, toMocked integrates seamlessly, easing the writing of tests.

Remember, in TypeScript, object represents non-primitive types. So, with toMocked, you're not confined to using plain objects; you can employ arrays and other complex types too.

function toMocked<T extends object>(value: any): T;
Enter fullscreen mode Exit fullscreen mode

Beneath the surface, toMocked capitalizes on the powerful JavaScript Proxy object to define custom behavior for property lookups. It checks if the accessed property exists on the target object. If it doesn't, it throws an error. If it does, the property is retrieved. If the property itself is an object, it gets wrapped in another level of proxy by recursively calling toMocked.

By doing so, it ensures your test data mimics the real thing as closely as possible, and your tests fail fast when expectations change. Therefore, if you're searching for a tool that can simplify your testing process by creating more realistic and maintainable mock data, @lifeiscontent/to-mocked is a worthy contender. Give it a try and notice the difference it brings to your testing workflow.

Top comments (0)