alan2207 / bulletproof-react

🛡️ ⚛️ A simple, scalable, and powerful architecture for building production ready React applications.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[question] How to mock APIs of a "composite" feature?

BreakBB opened this issue · comments

I just migrated a project to the bulletproof-react structure and have a question about mocking API calls.

Given structure:

- features/
  - foo/
    - api/
    - components/
      - Foo.tsx
    - hooks/
  - bar/
    - api/
    - components/
      - Bar.tsx

Now I want to test the component Bar which imports/uses Foo.

export const Bar = () => ({
   <Foo />
})

But Foo is doing API calls in a hook to fetch some data, which I want to mock.

Bar.test.ts:

import { Foo, fetchData } from "@/features/foo";

// This mocks the entire feature
vi.mock("@/features/foo");

// ... test

const fetchDataMock = fetchData;

Now the issue I have is, that I don't want to mock the entire @/feature/Foo module, but just the API calls of it.

Is there a "best practice" for this? I didn't find a matching example in the repo.

I know I can do vi.mock("@/features/foo/api/fetchData.ts");, but that seems inappropriate given the fact that every feature should export everything available to the outside in the index.ts.

Hey, you can register mocked API handlers for the foo module in your tests, and you should be good to go.

Something like this:

// @features/Bar/Bar.test.tsx

server.use(
  rest.get('/bar', () => {
    //...
  })
)

Check the docs here: https://mswjs.io/docs/api/setup-server/use

Thanks, I'll look into that. I also found, that it might not be really feasible to test these components as "unit test". Especially with a wide cypress test coverage.

@BreakBB It depends on how granular you want to go with testing. Integration testing might be better for testing different edge cases and E2E tests usually test the happy path of the whole application flow. You can and should still have both, but it's up to you...

Yeah, I will still respect the testing pyramid as good as possible, you are absolutely right. I just don't want to have a "testing cube" where every layer tests "everything" 😁