Как заставить navigator.geolocation.getCurrentPosition терпеть неудачу - PullRequest
0 голосов
/ 04 февраля 2020

Я использую API геолокации

// index.js

navigator.geolocation.getCurrentPosition(() => {...}, (err) => {
  handleError(err)
})

Давайте представим, что handleError поддразнивается в тестах.

// index.spec.js

it("should call error handler", () => {
  expect(handleError).toBeCalled()
})

Я бы хотел, чтобы navigator.geolocation.getCurrentPosition не работал в чтобы убедиться, что handleError вызывается.

Я использую Jest, так есть ли способ контролировать сбой getCurrentPosition?

1 Ответ

0 голосов
/ 05 февраля 2020

Вот решение для модульного тестирования, среда тестирования: node:

index.js:

import { handleError } from './errorHandler';

function main() {
  navigator.geolocation.getCurrentPosition(
    () => {
      console.log('success');
    },
    (err) => {
      handleError(err);
    },
  );
}

export { main };

errorHandler.js:

import { handleError } from './errorHandler';

function main() {
  navigator.geolocation.getCurrentPosition(
    () => {
      console.log('success');
    },
    (err) => {
      handleError(err);
    },
  );
}

export { main };

index.test.js:

import { main } from './';
import { handleError } from './errorHandler';

jest.mock('./errorHandler', () => {
  return { handleError: jest.fn() };
});

describe('60062574', () => {
  beforeEach(() => {
    global.navigator = { geolocation: { getCurrentPosition: jest.fn() } };
  });
  it('should handle error', () => {
    const mError = new Error('some error');
    global.navigator.geolocation.getCurrentPosition.mockImplementationOnce((successCallback, errorCallback) => {
      errorCallback(mError);
    });
    main();
    expect(navigator.geolocation.getCurrentPosition).toBeCalledWith(expect.any(Function), expect.any(Function));
    expect(handleError).toBeCalledWith(mError);
  });

  it('should handle success', () => {
    const logSpy = jest.spyOn(console, 'log');
    global.navigator.geolocation.getCurrentPosition.mockImplementationOnce((successCallback, errorCallback) => {
      successCallback();
    });
    main();
    expect(logSpy).toBeCalledWith('success');
    expect(navigator.geolocation.getCurrentPosition).toBeCalledWith(expect.any(Function), expect.any(Function));
  });
});

Результаты модульных испытаний со 100% покрытием:

 PASS  stackoverflow/60062574/index.test.js
  60062574
    ✓ should handle error (5ms)
    ✓ should handle success (17ms)

  console.log node_modules/jest-mock/build/index.js:814
    success

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.715s, estimated 5s

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  setupFilesAfterEnv: ['./jest.setup.js'],
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
  verbose: true,
};

Исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60062574

...