项目作者: pigulla

项目描述 :
Simple environment that disables all network connectivity via nock
高级语言: TypeScript
项目地址: git://github.com/pigulla/jest-environment-nock-axios.git
创建时间: 2019-09-12T06:12:08Z
项目社区:https://github.com/pigulla/jest-environment-nock-axios

开源协议:ISC License

下载


jest-environment-nock-axios

Mock all network requests in tests using nock.

Purpose

This environment ensures that no unmocked network requests are made (by calling nock’s disableNetConnect).
It also takes care of some additional setup required to support axios.

Installation

Install as usual with npm install -D jest-environment-nock-axios (or the yarn equivalent). Both
nock and axios are required as peer dependencies.

To run a test in this environment set the testEnvironment
option.

Gotchas

Jest by design doesn’t implement the require cache. This means that the nock module configured by the environment is different from the module your tests get. To solve this that instance is injected into the global scope (see the example below).

Tips

It’s a good idea to verify test that no mocked requests are pending. One way to do that is to run the
following code after each test (e.g. using Jest’s
setupFilesAfterEnv) config option:

  1. const nock = global.nock; // See the 'Gotcha' section above
  2. afterEach(function () {
  3. const pendingMocks = nock.pendingMocks();
  4. if (pendingMocks.length > 0) {
  5. throw new Error(`There are still ${pendingMocks.length} pending mocks: ${pendingMocks.join()}`);
  6. }
  7. });

Example

  1. /**
  2. * @jest-environment nock-axios
  3. */
  4. import axios from 'axios';
  5. describe('This test', function () {
  6. const nock = global.nock; // See the 'Gotcha' section above
  7. it('will pass', async function () {
  8. nock('http://test.invalid')
  9. .get('/data.json')
  10. .reply(200, { name: 'Hairy Potter' });
  11. const result = await axios.get('http://test.invalid/data.json');
  12. expect(result.data).toEqual({ name: 'Hairy Potter' });
  13. });
  14. it('will fail', async function () {
  15. // ...because the host is not mocked
  16. await axios.get('http://news.ycombinator.com');
  17. });
  18. it('will fail if the above "setupFilesAfterEnv" hook is configured', async function () {
  19. await nock('http://test.invalid')
  20. .get('/no-data.json')
  21. .reply(200, {});
  22. // The mocked endpoint is never requested.
  23. });
  24. })