Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock network calls in test #24

Merged
merged 4 commits into from Oct 19, 2021
Merged

Conversation

il3ven
Copy link
Contributor

@il3ven il3ven commented Oct 19, 2021

Closes #14

  • I have used esmock along with fetch-mock. I could have skipped fetch-mock and mocked the transport.js module but then the tests would have lost their purpose.
  • I have tried mocking network calls strictly. Instead of sending a response for any call I check for the method, URL and body.
  • There are still network calls for the readme tests.

A brief explanation of the syntax.

const { default: getBlockNumber } = await esmock(
  "../src/blockNumber.js", // Module to be mocked
  null,
  {
   // Mock cross-fetch where ever it is imported
    "cross-fetch": {
      // This fetch-mock instance is the default export of cross-fetch
      default: fetchMock.sandbox().post(
        // Matcher object
        {
          url: options.url,
          body: {
            method: "eth_blockNumber",
          },
          matchPartialBody: true,
        },
        // Response object
        {
          result: "0xcd2057",
        }
      ),
    },
  }
);

test/blockNumber_test.js Outdated Show resolved Hide resolved
cjs/index.js Outdated Show resolved Hide resolved
cjs/index.js Outdated Show resolved Hide resolved
Copy link
Contributor

@TimDaub TimDaub left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! Thanks.

I'll merge once you have addressed the two superfluous console.logs in index.js

@TimDaub TimDaub merged commit 41668a2 into attestate:master Oct 19, 2021
1 check passed
@il3ven il3ven deleted the mockNetworkCall branch October 19, 2021 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Mock all network functionality in tests
2 participants