Jest Automatic-Mocks: забавный пример результата - PullRequest
0 голосов
/ 20 сентября 2019

это относится к примеру Facebook учебные пособия

// utils.js
// Copyright 2004-present Facebook. All Rights Reserved.

export default {
  authorize: () => 'token',
  isAuthorized: (secret) => secret === 'wizard',
};

ниже - тестовый файл.Вместо того, чтобы добавить auto mock к файлу конфигурации, я добавил код, чтобы показать различия.

import utils from './utils';

jest.enableAutomock();

test('implementation created by automock', () => {
  expect(utils.authorize('wizzard')).toBeUndefined();
  expect(utils.isAuthorized()).toBeUndefined();
});

результат:

TypeError: Cannot read property 'default' of undefined

   6 | 
   7 | test('implementation created by automock', () => {
>  8 |   expect(utils.authorize('wizzard')).toBeUndefined();
     |          ^
   9 |   expect(utils.isAuthorized()).toBeUndefined();
  10 | });
  11 | 

  at Object.utils (__tests__/example/automatic-mocks/genMockFromModule.test.js:8:10)

Почему это так?это происходит с другим файлом automock.test.js.Сообщение об ошибке то же самое.

// Copyright 2004-present Facebook. All Rights Reserved.

import utils from './utils';

jest.enableAutomock();

test('if utils are mocked', () => {
  expect(utils.authorize.mock).toBeTruthy();
  expect(utils.isAuthorized.mock).toBeTruthy();
});

test('mocked implementation', () => {
  utils.authorize.mockReturnValue('mocked_token');
  utils.isAuthorized.mockReturnValue(true);

  expect(utils.authorize()).toBe('mocked_token');
  expect(utils.isAuthorized('not_wizard')).toBeTruthy();
});

1 Ответ

0 голосов
/ 28 сентября 2019

Приведенный ниже пример работает для меня, я использую jestjs с typescript и ts-jest.

документы говорят:

Примечание: этот метод ранее назывался autoMockOn,При использовании babel-jest вызовы enableAutomock будут автоматически перемещаться в верхнюю часть блока кода.Используйте autoMockOn, если вы хотите явно избежать этого поведения.

utils.ts:

const utils = {
  getJSON: data => JSON.stringify(data),
  authorize: () => 'token',
  isAuthorized: secret => secret === 'wizard'
};

export default utils;

utils.spec.ts:

jest.enableAutomock();

import utils from './utils';

describe('automatic mocks test suites', () => {
  it('should mock all methods of utils', () => {
    expect((utils.getJSON as jest.Mock).mock).toBeTruthy();
    expect(jest.isMockFunction(utils.authorize)).toBeTruthy();
    expect(jest.isMockFunction(utils.isAuthorized)).toBeTruthy();
  });

  test('implementation created by automock', () => {
    expect(utils.authorize()).toBeUndefined();
    expect(utils.isAuthorized('wizard')).toBeUndefined();
  });

  it('mocked implementation', () => {
    (utils.getJSON as jest.Mock).mockReturnValue(123);
    expect(utils.getJSON({ name: 'test' })).toBe(123);
  });
});

Результат модульного теста:

 PASS  src/automatic-mocks/utils.spec.ts (17.906s)
  automatic mocks test suites
    ✓ should mock all methods of utils (4ms)
    ✓ implementation created by automock (2ms)
    ✓ mocked implementation (1ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        22.923s, estimated 23s

Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/automatic-mocks

...