Модульное тестирование экспортированных функций модуля - PullRequest
0 голосов
/ 04 октября 2019

Попытка модульного тестирования функций внутри экспортируемого модуля с помощью Jest

Модуль выглядит следующим образом:


export default {

  errorNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'error',
      title: title,
      text: text
    })
  },

  infoNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'info',
      title: title,
      text: text
    })
  },

  successNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'success',
      title: title,
      text: text
    })
  },

  warningNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'warning',
      title: title,
      text: text
    })
  }
}

Тест, который я пытаюсь написать,:

import notifications from '@/services/notifications.service'

describe('Notifications tests', () => {
  test('successNotification should set title to title and text to text ', () => {
    let title = 'test'
    let text = 'test'

    //let successNotification = jest.fn()

    notifications.successNotification(title, text)
    expect(title).toEqual('test')
    expect(text).toEqual('test')
  })
})

Когда я запускаю это, я получаю следующую ошибку:

Ошибка типа: _vue.default.notify не является функцией

СейчасНасколько я понимаю, ошибка из-за того, что я не издеваюсь _vue.default.notify, однако я не уверен, как на самом деле это сделать. Некоторая помощь будет оценена.

1 Ответ

1 голос
/ 05 октября 2019

Вы можете смоделировать модуль Vue вручную, используя jest.mock(moduleName).

Например:

index.ts:

import Vue from './Vue';

export default {
  errorNotification(title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'error',
      title: title,
      text: text
    });
  },

  infoNotification(title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'info',
      title: title,
      text: text
    });
  },

  successNotification(title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'success',
      title: title,
      text: text
    });
  },

  warningNotification(title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'warning',
      title: title,
      text: text
    });
  }
};

Vue.ts: я создаюмодуль Vue для имитации реального модуля Vue.

export default {
  notify(payload) {
    //
  }
};

index.spec.ts:

import notifications from './';
import Vue from './Vue';

jest.mock('./Vue.ts');

describe('Notifications tests', () => {
  test('successNotification should set title to title and text to text ', () => {
    Vue.notify = jest.fn().mockReturnValueOnce({});
    const title = 'test';
    const text = 'test';

    notifications.successNotification(title, text);
    expect(Vue.notify).toBeCalledWith({
      group: 'max-fordham',
      type: 'success',
      title,
      text
    });
  });
});

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

 PASS  src/stackoverflow/58239972/index.spec.ts
  Notifications tests
    ✓ successNotification should set title to title and text to text  (12ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.773s
...