在测试使用moment.tz(time)功能的方法时,我得到了__WEBPACK_IMPORTED_MODULE_2_moment__.tz is not a function。当我测试一个使用moment.js的伪函数时,一切都是正常的。
我检查了因果报应和webpack的配置,但他们没有提到任何地方的时刻。根据我的推理,如果moment在像这样的单元测试中工作,而不是在webpack和karma配置中明确提到,那么moment-timezone也应该如此。
以下是服务的单元测试文件:
//note.service.spec.ts
import {TestBed, inject} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from "@angular/platform-browser-dynamic/testing";
import {NoteService} from './note.service';
import * as moment from 'moment'; //xavtodo: maybe not needed
describe('NoteService', () => {
let service: NoteService;
beforeEach(() => {
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
.configureTestingModule({
providers: [NoteService]
});
});
afterEach(() => {
TestBed.resetTestEnvironment();
});
beforeEach(inject([NoteService], (s: NoteService) => {
service = s;
}));
it('should be created', inject([NoteService], (service: NoteService) => {
expect(service).toBeTruthy();
}));
it('DUMMY WITH MOMENTJS', inject([NoteService], (service: NoteService) => { //so this one is working with moment.js
expect(service.dummy()).toBeTruthy();
}));
it('DUMMY WITH MOMENT-TIMEZONE', inject([NoteService], (service: NoteService) => { //this one isn't with moment timezone
expect(service.dummytz()).toBeTruthy();
}));
});我正在测试的用于隔离错误的note.service.ts中的dummy和dummytz函数:
dummy(): Moment{
return moment();
}
dummytz(): Moment{
return moment.tz('Europe/London');
}显然,看起来tz()函数不是在moment上定义的,在单元测试中,webpack不会选择moment-timezone,但在应用程序中它会选择它。
这是webpack.unit.test.js配置文件:
const webpack = require('webpack');
const helpers = require('./helpers');
const commonConfig = require('./webpack.common.js');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
console.log('///////////////////////////UNIT TEST');
module.exports = {
devtool: 'inline-source-map',
node: {
fs: 'empty'
},
resolve: {
extensions: ['.ts', '.js']
},
module: commonConfig.module,
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new ExtractTextPlugin({ filename: 'main.css', disable: false, allChunks: true})
]
}发布于 2018-02-11 09:34:41
如何以及在哪里导入moment?看起来你好像失踪了
var moment = require('moment-timezone');有关如何使用moment().tz的更多详细信息are here
https://stackoverflow.com/questions/48708582
复制相似问题