CEKREM . GITHUB . IO

Dependency Inversion in React: Building Truly Testable Components

#react #clean architecture #testing #solid-principles

In the world of React development, we often find ourselves writing components that are tightly coupled to their dependencies. This makes testing difficult, maintenance a challenge, and change nearly impossible. The Dependency Inversion Principle (DIP) offers a way out of this mess, but how do we apply it effectively in React?

Note: For a more backend-oriented take on Dependency Inversion, check out my previous post on Dependency Inversion in Go Using Plugins.

The Problem: Tight Coupling in React

Consider this common scenario:

 1const UserProfile = () => {
 2  const [user, setUser] = useState(null);
 3  const [loading, setLoading] = useState(true);
 4
 5  useEffect(() => {
 6    fetch("/api/user")
 7      .then((res) => res.json())
 8      .then((data) => {
 9        setUser(data);
10        setLoading(false);
11      });
12  }, []);
13
14  if (loading) return <LoadingSpinner />;
15  return <UserDetails user={user} />;
16};

This component has several problems:

Michael Scott sad

The Solution: Dependency Inversion

The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions. In React, this means our components should depend on interfaces, not concrete implementations.

Let’s see how we can refactor this:

 1interface UserRepository {
 2  getUser: () => Promise<User>;
 3}
 4
 5const UserProfile = ({
 6  userRepository,
 7}: {
 8  userRepository: UserRepository;
 9}) => {
10  const [user, setUser] = useState<User | null>(null);
11  const [loading, setLoading] = useState(true);
12
13  useEffect(() => {
14    userRepository.getUser().then((data) => {
15      setUser(data);
16      setLoading(false);
17    });
18  }, [userRepository]);
19
20  if (loading) return <LoadingSpinner />;
21  return <UserDetails user={user} />;
22};

(You could of course consider extracting all this state + useEffect stuff into a custom hook, but that’s beside the point at this point.)

Implementing the Repository

Now we can create concrete implementations of our repository:

 1class ApiUserRepository implements UserRepository {
 2  async getUser(): Promise<User> {
 3    const response = await fetch("/api/user");
 4    return response.json();
 5  }
 6}
 7
 8class MockUserRepository implements UserRepository {
 9  private resolveUser: (user: User) => void = () => {};
10  private rejectUserPromise: (error: Error) => void = () => {};
11
12  getUser(): Promise<User> {
13    return new Promise((resolve, reject) => {
14      this.resolveUser = resolve;
15      this.rejectUserPromise = reject;
16    });
17  }
18
19  // Helper method to resolve the promise
20  resolveWithUser(user: User) {
21    this.resolveUser(user);
22  }
23
24  // Helper method to reject the promise
25  rejectUser(error: Error) {
26    this.rejectUserPromise(error);
27  }
28}

Testing Made Easy

With this structure, testing becomes straightforward:

 1describe("UserProfile", () => {
 2  it("shows loading state initially", () => {
 3    const mockRepo = new MockUserRepository();
 4    render(<UserProfile userRepository={mockRepo} />);
 5    expect(screen.getByTestId("loading-spinner")).toBeInTheDocument();
 6  });
 7
 8  it("displays user data when loaded", async () => {
 9    const mockRepo = new MockUserRepository();
10    render(<UserProfile userRepository={mockRepo} />);
11
12    // Simulate data fetching
13    mockRepo.resolveWithUser({
14      id: 1,
15      name: "Test User",
16      email: "test@example.com",
17    });
18
19    const userData = await screen.findByText("Test User");
20    expect(userData).toBeInTheDocument();
21  });
22
23  // Testing exceptions would be equally stragihtforward, but excluded for brevity
24});

Best Practices

  1. Define Clear Interfaces: Create interfaces that represent your dependencies
  2. Inject Dependencies: Pass dependencies as props or through context, or better yet using TSyringe
  3. Test in Isolation: Each component should be testable without its dependencies

Conclusion

Applying the Dependency Inversion Principle in React leads to:

Remember: The goal isn’t to add complexity, but to make your code more maintainable and testable. Start small, and apply these principles where they make the most sense.

Michael Scott happy

Further Reading

Note on Dependency Injection

While this guide focuses on applying the Dependency Inversion Principle in React, we won’t delve into the specifics of implementing dependency injection in a clean and scalable manner. However, if you’re interested in exploring this further, libraries like TSyringe provide a good starting point for managing dependencies effectively in your React applications.

Reply to this post by email ↪