Apollo reactive variables - how to mock value of the variables into a component during testing
Asked Answered
S

1

8

I need some help. I'm a newbie in apollo client reactive variables. There is a component where the displaying of the message depends on a variable that values from the local state (apollo cache). How will be mock apollo cache during testing the component that passes different values into this variable?

Message.tsx

const Message: FC = ({ children }) => {
  const message = useReactiveVar(messageVar);

  return (
    <>
      {!!message && (
        <Alert>
          <Typography className={classes.title}>
            Due to scheduled data updates...
          </Typography>
        </Alert>
      )}
      {children}
    </>
  );
};

cache.ts

export const cache: InMemoryCache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        maintenanceMessage: {
          read() {
            return messageVar();
          },
        },
      },
    },
  },
});

const maintenanceMessageVar = makeVar<null>(null)

Message.test.tsx

it('render message', () => {
const { getByText } = render(
  <MockedProvider
    mocks={mock}
    cache={cache}
    addTypename={true}
  >
    <Message>
     <h4>Header</h4>
    </Message>
  </MockedProvider>,
);

getByText('Due to scheduled data updates...');

});
Semivitreous answered 23/3, 2021 at 8:23 Comment(0)
S
2

You can set those reactive variables before rendering the component.

For example:

it('render message', () => {
  messageVar(true);
  
  const { getByText } = render(
  <MockedProvider
    mocks={mock}
    cache={cache}
    addTypename={true}
  >
    <Message>
     <h4>Header</h4>
    </Message>
  </MockedProvider>,
);
Saturnalia answered 28/4, 2022 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.