How can I mock a realistic response from the Apollo Client?

Hello, I am currently trying to make tests using the Apollo Client and I would like to get realistic mocked responses from the Apollo Client. I would like to create a class that returns mock responses from the Apollo Client but haven’t quite figured out how to do this. Is there a better way to accomplish this or am I missing something from the docs?

For example, this is what I am trying to accomplish:

@Test func example() async throws {
        let mockUser = Mock<User>()
        mockUser.userid = "123"
        mockUser.name = "Tester"
        let mockData = GetUserQuery.Data.from(mockUser)
        let mockRepo = MockNetworkRepo()
        mockRepo.mockQueryData = mockData
        Container.shared.network.register { mockRepo }
        
        let viewModel = UserDetailVM()
        viewModel.fetchUser()

        // Then
        #expect(viewModel.name == "Tester")
    }

This is how my mock network is working:

class MockNetworkRepo: NetworkRepo {
    
    // MARK: - Configurable Mock Behavior
    var mockMutationData: Any?
    var mockQueryData: Any?
    var mockError: Error?

func query<Query: GraphQLQuery>(
        _ query: Query,
        cachePolicy: CachePolicy,
        contextIdentifier: UUID?,
        queue: DispatchQueue,
        resultExpected: Bool,
        completion: @escaping (Result<Query.Data?, Error>) -> Void
    ) -> Cancellable {

        queue.async {
            if let error = self.mockError {
                onError?()
                completion(.failure(error))
            } else if let data = self.mockQueryData as? Query.Data { // This returns as nil. 
                completion(.success(data))
            } else {
                completion(.success(nil))
            }
        }

        return MockCancellable()
    }
}

Hi @Hunter_Freas - The bad news is that unfortunately there really is no easy way to do this at the moment. The good news is that we’re planning to address this in the upcoming 2.0 version (a couple weeks ago we published a preview branch - no testing framework in there yet though).

We do have internal classes that we use for testing but have never made them publicly available. Take a look and hopefully they can better guide you.

1 Like

Thanks for the response, I look forward to version 2.0.

In the meantime, I’ll try out the internal classes you shared.