使用Jasmine和Moment.js获取错误moment.moment不是一个函数

时间:2017-10-14 19:01:45

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

我正在尝试将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上找到的东西,并且正在尝试......我还安装了一个像这样的业力时刻插件:

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

插件:[       '果报的jquery&#39 ;,       '果报browserify&#39 ;,       '卡玛时刻&#39 ;,       '果报茉莉&#39 ;,       '因缘 - 铬 - 发射&#39 ;,       '卡玛 - 茉莉HTML的记者'     ]

2 个答案:

答案 0 :(得分: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模块,则不太容易导致问题。

答案 1 :(得分:0)

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

我在script.js文件中更改了此内容: 从'时刻'导入{时刻};

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