【问题标题】:getting an error moment.moment is not a function, using Jasmine and Moment.js得到错误 moment.moment 不是函数,使用 Jasmine 和 Moment.js
【发布时间】:2017-10-14 19:01:45
【问题描述】:

我正在尝试将 Jasmine 与 moment.js 结合使用,但出现此错误...

 debug.js:21 Uncaught TypeError: (0 , _moment.moment) is not a function

不确定它是否与 moment.js 相关,或者我是否设置不正确。感谢任何帮助。

//script.js

import { moment } from 'moment';

export class Age {
  
  constructor(age, secondDate) {
    this.age = age;
    this.secondDate = secondDate;
  }

  getSecondsBetweenTwoDates(age, secondDate){
    age = moment(this.age).format('l');
    secondDate = moment(this.secondDate).format('l');
    //differenceInSeconds = moment((this.secondDate).diff(this.age, 'days'));
    differenceInDays = age.diff(secondDate, 'days');
    //let differenceInDays = this.age - this.secondDate
    return differenceInDays;

  }
}


//age-spec.js

import { Age } from './../js/age.js';

describe('Age', function() {
  
  let reusableDate,
      today,
      testDate = '2016-10-05',
      date = '2016-10-10';

  beforeEach(() => {
    reusableDate = new Age(date, testDate);
    console.log(reusableDate);
    const mockedDateAndTime  = '2017-03-02 00:00:00';
    today = moment(mockedDateAndTime).toDate();
    console.log('this is today', today);
    jasmine.clock().mockDate(today);
  });

  it('should return the difference between today', () => {
    console.log(date);
    console.log(testDate);
    console.log(reusableDate.getSecondsBetweenTwoDates(date, testDate));
    console.log(typeof(reusableDate.getSecondsBetweenTwoDates));
    //expect(5).toEqual(reusableDate.getSecondsBetweenTwoDates());
  });


});

我根本没有使用 beforeEach 块,这只是我在 Google 上找到的东西,并且正在尝试......我还安装了一个 karma-moment 插件,如下所示:

框架:['jquery-3.2.1', 'jasmine', 'browserify', 'moment-2.9.0'],

插件:[ '业力 jquery', '业力浏览', '业力时刻', '业力茉莉', '业力铬发射器', '业力-茉莉花-html-记者' ]

【问题讨论】:

    标签: unit-testing ecmascript-6 jasmine momentjs karma-jasmine


    【解决方案1】:

    moment 包中没有 moment 命名导出。大多数 NPM 包都是 CommonJS/UMD,它们的主要导出为 module.exports。即使moment 写成as ES module with default export,它也可以作为UMD 模块导入,因为它有different entry points for different environments

    应该是

    import * as moment from 'moment';
    

    import moment from 'moment';
    

    选择可能取决于项目配置。一般来说,* as 更好地反映了真正的 CommonJS 导出,并且如果项目在捆绑期间配置为回退到 CJS 模块,则不太容易出现问题。

    【讨论】:

    • 感谢您的回答,我不知道。
    【解决方案2】:

    我犯了一个愚蠢的错误,由于某种原因,我在文件顶部的 ES6 导入语法不起作用。

    我在我的 script.js 文件中更改了这个: 从“时刻”导入{时刻};

    对此: var moment = require('moment');

    【讨论】:

    • 由于非常具体的原因它不起作用。因为没有 moment 命名的导出。
    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2019-12-17
    相关资源
    最近更新 更多