单元测试导出的模块功能

ba

尝试借助以下工具对导出的模块中的功能进行单元测试 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')
  })
})

运行此命令时,出现以下错误:

TypeError:_vue.default.notify不是一个函数

现在,据我了解,该错误是由于我没有嘲笑引起的_vue.default.notify,但是,我不确定如何实际执行该操作。一些帮助将不胜感激。

幻灯片放映

您可以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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章