question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow mocking and typing

See original GitHub issue

swr looks really cool 👍

I played around with something similar for request-registry recently.

What I miss in swr over request-registry is the ability to define typings, dependencies and to mock
I would love to know what you think about those features.

Define typings once per endpoint

In request registry you define endpoints e.g.:

import { createGetEndpoint } from "request-registry";
 
// Define a service endpoint to load user information
const userEndpoint = createGetEndpoint<{id: string}, {name: string, age: number}>({
    url: keys => `http://example.com/user/${keys.id}`
});

Then you can use them from a hook e.g.


import {useGetEndPointSuspendable} from 'request-registry-react';

const UserDetails = props => {
    const { name } = useGetEndPointSuspendable(userEndpoint, { id: props.id });
    return <div>{name}</div>;
};

It also works without suspense similar to the swr api:

const UserDetails = props => {
    const endpointState = useGetEndPoint(userEndpoint, { id: props.id });
    if (!endpointState.hasData) {
        return <div>Loading...</div>;
    }
    const { name } = endpointState.value;
    return <div>{name}</div>;
};

This allows autocomplete and type checking for endpointState.value without writing additional endpoint specific types inside the UserDetails component.

Dependencies

Endpoints can also cause mutations e.g.:

import { createPostEndpoint } from "request-registry";
 
// Define a mutation endpoint
const mutateUser = createPostEndpoint<{id: string}, {name: string}, {}>({
    url: keys => `http://example.com/user/${keys.id}`
    // Invalidate all userEndpoint endpoints (similar to your trigger broadcast)
    afterSuccess: () => userEndpoint.refresh()
});

// now for example inside an eventHandler 
  <button onClick={async () => {
      const newName = data.name.toUpperCase()
      // update user 4 and rerender all components which rely on user 4 data:
      await mutateUser(newName)
    }}>

Mocking

For unit tests and storybook we sometimes want to tryout specific scenarios and want to mock backend responses.

// Define your mock data for getUserName
// Typescript will tell you if the mock data doesn't match the types for
// getUserName
const userJoeMock = createMockEndpoint(getUserName, async () => ({
    name: 'Joe',
}));

Now in any unit test or story you can activate the mock:

// Activate mock:
userJoeMock.activate();
// Deactivate mock:
userJoeMock.clear();

There are more utils around this but maybe this is enough to get the basic idea.

I would love to know what you think about those features. 😃

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:10 (6 by maintainers)

github_iconTop GitHub Comments

9reactions
sergiodxacommented, Oct 29, 2019

I think you could create a custom hook using SWR internally and define the types there.

type User = {
  id: number,
  displayName: string
}

function useUser(id: number): { data: User } {
  return useSWR(`/api/users/${id}`, fetch);
}

function UserProfile({ id }: { id: number }) {
  const { data } = useUser(id);
  return <p>{data.displayName}</p>
}

Something like this, and if you move this custom hook to another file you could mock it in your tests.

4reactions
sergiodxacommented, Oct 29, 2019

In just you could do:

import useUser from "path/to/hooks/api/use-user";

jest.mock("path/to/hooks/api/use-user");

useUser.mockImplementation(() => ({
  data: {
    displayName: "sergio", id: 1
  }
}));

Something like that will mock useUser module and let you mock the implementation to return fake data immediately, you could also run mockImplementation multiple times to change what it will return.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Avoid type warnings when mocking objects in unit tests?
I'm going to put my 2¢ in and say that you should type-check your testsuite. Its still code and static type checking will...
Read more >
Types and Mocking - Typescript - DEV Community ‍ ‍
In this article, we are going to learn how to create functions which are easy to test and mock using TypeScript utility types....
Read more >
New app makes typing mOcKiNg SpOnGeBoB mEmE text ...
Samir Mezrahi made an app called sPoNgEcAsE, which allows people to effortlessly type Mocking Spongebob Meme text.
Read more >
unittest.mock — mock object library — Python 3.11.1 ...
It allows you to replace parts of your system under test with mock objects and make assertions about ... Instead you can attach...
Read more >
Creating Mock Classes
This allows ON_CALL and EXPECT_CALL to reference the mock function from outside ... To ensure safety, Google Mock checks that (let U be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found