apollographql / apollographql/graphql-testing-library

How to deal with Fragments?

Open
#163 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
61
Forks
2
PR merge metrics
No merged PRs in 30d

Description

Given I'm mocking a query like this:
```ts
const createTx: () => schema.Transaction = () => ({ value: 'txValue' })
mockRequestHandler.withResolvers({
Query: {
transactions: () => createTx()
}
})
```

Then I'm reusing the `createTx` in my tests like this:
```ts
render()
...userEvent, expect, etc
```

But there's an alias in my actual query:
```graphql
transactions {
...Tx
}

fragment Tx on Transaction {
value: myValue
}
```

So, while in the `` component, I'm not getting `myValue` since `createTx` returns an object with `value` instead.

I am using graphql-codegen, so I have `TxFragment` type available, but I don't see how I can convert the raw type (`schema.Transaction`) into the fragment. What's the recommended approach?

Here's my workaround:
```ts
const createTx: () => schema.Transaction & Pick = () => ({ value: 'txValue', myValue: 'txValue' })
```
Just hardcoding specific differences so that type casting works in both places. But it's a hack

Contributor guide

No contributing guide indexed for this repository

Research direction

Compare the generated TxFragment type with schema.Transaction and the fragment spread shown in the query. Review mockRequestHandler.withResolvers and the test setup; done means the repository has a clear, tested recommendation for creating reusable mocked data that works with both representations.

Written by the indexing model from the issue text.

Assessment

Tech stack
graphql, typescript
Domain
testing
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.