【问题标题】:Why is my Vue unit test not recognizing a function?为什么我的 Vue 单元测试无法识别函数?
【发布时间】:2020-03-18 02:00:45
【问题描述】:

我目前正在为包含函数 formatDateGlobal 的组件 dateFormat.js 编写简单的单元测试(使用 Jest)。这是测试的sn-p:

import DateFormat from '../dateFormat';

describe('dateFormat.js', () => {
  let date1;

  beforeEach(() => {
    date1 = {
      date: '',
    };
  });

  it('Then it should return an empty string', () => {
    // Act
    const returnedDate = DateFormat.formatDateGlobal(date1);
    // Assert
    expect(returnedDate).toBe('');
  });

在 dateFormat 的底部,我将 formatDateGlobal 函数导出为:

export default formatDateGlobal;

测试按预期构建,但出现错误

TypeError: _dateFormat.default.formatDateGlobal is not a function

      27 |   it('Then it should return an empty string', () => {
      28 |     // Act
    > 29 |     const returnedDate = DateFormat.formatDateGlobal(date1);
         |                                     ^
      30 |     // Assert
      31 |     expect(returnedDate).toBe('');
      32 |   });

不太清楚为什么会发生这种情况,但我认为这与我导出函数的方式有关。

【问题讨论】:

    标签: javascript unit-testing vue.js jestjs


    【解决方案1】:

    您正在将 formatDateGlobal 导入到 DateFormat 变量中。所以你可以使用 const returnedDate = DateFormat(date1);

    目前您正在尝试实现与此等价的效果: const returnedDate = formatDateGlobal.formatDateGlobal(date1);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 2021-01-11
      • 2021-03-30
      • 1970-01-01
      • 2021-12-08
      • 2018-03-28
      相关资源
      最近更新 更多