首页 > 解决方案 > How to use momentJs in Karma/Jasmine unit tests for AngularJS?

问题描述

I am using momentJS in my AngularJS project.

I am trying to write unit tests and I keep getting issues with moment.

Here is my config file:

// list of files / patterns to load in the browser
files: [
    // './bower_components/moment/min/moment.min.js',
    // './bower_components/moment-timezone/builds/moment-timezone.min.js',
    // './bower_components/moment/min/moment-with-locales.js',
    // './bower_components/moment-timezone/builds/moment-timezone-with-data.js',
    './bower_components/moment/moment.js',
    './bower_components/moment-timezone/moment-timezone.js',

    './source/builds/vendors.js',
    './node_modules/angular-mocks/angular-mocks.js',
    './source/builds/vendors.css',
    './source/builds/app.css',
    './source/builds/bundle.js',
    './source/js/**/*.spec.js'
],

I keep getting this error: TypeError: moment(...).year(...).week is not a function

I'm not sure how to fix the error.

标签: angularjsunit-testingmomentjskarma-jasmine

解决方案


为了立即运行单元测试,我们首先需要检查的是将 moment.js 和 angular-moment.js 文件包含在配置文件中

files: [
    '../bower_components/moment/moment.js',
    '../bower_components/angular-moment/angular-moment.js',
]

之后在规范文件上

describe('Moment Tests', function() {
    var _moment;
    beforeEach(inject(function(moment) {
        _moment: moment
    }));
});


describe('Test for date by provided format', function (){

    it('should return date by provided format', function() {
        var expectedYear = _moment(new Date().year());
        expect(2019).toEqual(expectedDate);
    });
});

希望这会有所帮助。


推荐阅读