relay icon indicating copy to clipboard operation
relay copied to clipboard

Cannot generate null value for type without mocking parent

Open chrisdarroch opened this issue 3 years ago • 4 comments

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

chrisdarroch avatar Mar 03 '22 04:03 chrisdarroch