Skip to content

Instantly share code, notes, and snippets.

@JustenRickert
Last active July 19, 2018 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustenRickert/5040a6d9564de8ed60f50a0f482a4508 to your computer and use it in GitHub Desktop.
Save JustenRickert/5040a6d9564de8ed60f50a0f482a4508 to your computer and use it in GitHub Desktop.
jest running problem

The Problem

JavaScript doesn't want to support mutual recursion within our testing environment. So, the below function fails while running our test suite.

const selectPersistedContext = (state: RootState) => {
  const advisors = selectAdvisors(state); // selectAdvisors undefined
  const context = selectPersistedContext(state); // selectPersistedContext undefined
  const { fmid } = context;
  if (fmid) {
    const advisor = advisors.find(advisor => advisor.fmid === fmid);
    return advisor || Advisor.create({ fmid });
  }
  return undefined;
};

It fails because selectAdvisors and selectPersistedContext come from different files, which JavaScript believes to imply mutual recursion (which it thinks it doesn't support) and so it fails.

The problem can be eleviated by delaying supplying the selectAdvisors and selectPersistedContext. Like so:

const gradualSelectPersistedAdvisor = (
  selectAdvisors: Function,
  selectPersistedContext: Function,
) => (state: RootState) => {
  const advisors = selectAdvisors(state);
  const context = selectPersistedContext(state);
  const { fmid } = context;
  if (fmid) {
    const advisor = advisors.find(advisor => advisor.fmid === fmid);
    return advisor || Advisor.create({ fmid });
  }
  return undefined;
};

where then the actual selectAdvisors and selectPersistedContext functions can be pulled in from the test file using require.requireActual or mocking them out.

The old selector function can then be written easily like so:

const selectPersistedAdvisor = gradualSelectPersistedAdvisor(
  selectAdvisors,
  selectPersistedContext,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment