facebook / relay

Relay is a JavaScript framework for building data-driven React applications.
https://relay.dev
MIT License
18.38k stars 1.82k forks source link

Cannot generate null value for type without mocking parent #3825

Open chrisdarroch opened 2 years ago

chrisdarroch commented 2 years ago

Assuming the following schema:

type Query {
  fields: [Field!]!
}

interface Field {
  id: ID!
}

type FooField implements Field {
  sub: SubFoo
}

type SubFoo {
  name: String!
}

and I have a query as follows:

query ExampleQuery {
  fields {
    ...myFooFragment
  }
}

fragment myFooFragment on FooField {
  sub {
    name
  }
}

It's valid for this query to return null for the sub key.

When I mock that in a test as follows:

    environment.mock.queueOperationResolver((operation) =>
        MockPayloadGenerator.generate(operation, {
            SubFoo: () => null,
        })
    );

I would expect this to set the sub key to null in the response. What I'm seeing, though, is a generated value:

{ sub: { name: '<mock-value-for-field-"name">' } }

If I instead do this, it works...

    environment.mock.queueOperationResolver((operation) =>
        MockPayloadGenerator.generate(operation, {
            FooField: () => ({ sub: null }),
        })
    );

I get the expected value:

{ sub: null }

But since not every key will have a nested key to null out, this isn't a general solution.

I think this line is in error; instead of using a nullish coalescing operator, it should be explicitly testing for undefined so that null values are accepted from the generator functions. https://github.com/facebook/relay/blame/98162d36249cbdb162155427c0d721192de78d81/packages/relay-test-utils/RelayMockPayloadGenerator.js#L712

michael-haberzettel commented 1 year ago

Any update on this topic? I have the same issue and it's can be annoying with deep query.

rarenatoe commented 11 months ago

Shameless bump. I'm having the same issue too.

ling1726 commented 2 months ago

Also a shameless bump

susannasouv commented 2 months ago

And a shameful bump