【发布时间】:2017-06-23 15:30:58
【问题描述】:
我正在使用 angular 1.6、typescript、webpack、karma 和 jasmine 编写应用程序。我能够为角度服务创建单元测试,但现在我在测试组件时遇到了麻烦。在 SO(1) 和 (2) 以及网络上,我发现了不同的示例 (like this),但没有明确的指南解释如何使用上述技术集测试 angular 1 组件。
我的组件(HeaderComponent.ts):
import {IWeatherforecast} from '../models/weather-forecast';
import WeatherSearchService from '../search/weather-search.service';
import WeatherMapperService from '../common/mapping/weatherMapper.service';
export default class HeaderComponent implements ng.IComponentOptions {
public bindings: any;
public controller: any;
public controllerAs: string = 'vm';
public templateUrl: string;
public transclude: boolean = false;
constructor() {
this.bindings = {
};
this.controller = HeaderComponentController;
this.templateUrl = 'src/header/header.html';
}
}
export class HeaderComponentController {
public searchText:string
private weatherData : IWeatherforecast;
static $inject: Array<string> = ['weatherSearchService',
'$rootScope',
'weatherMapperService'];
constructor(private weatherSearchService: WeatherSearchService,
private $rootScope: ng.IRootScopeService,
private weatherMapperService: WeatherMapperService) {
}
public $onInit = () => {
this.searchText = '';
}
public searchCity = (searchName: string) : void => {
this.weatherSearchService.getWeatherForecast(searchName)
.then((weatherData : ng.IHttpPromiseCallbackArg<IWeatherforecast>) => {
let mappedData = this.weatherMapperService.ConvertSingleWeatherForecastToDto(weatherData.data);
sessionStorage.setItem('currentCityWeather', JSON.stringify(mappedData));
this.$rootScope.$broadcast('weatherDataFetched', mappedData);
})
.catch((error:any) => console.error('An error occurred: ' + JSON.stringify(error)));
}
}
单元测试:
import * as angular from 'angular';
import 'angular-mocks';
import HeaderComponent from '../../../src/header/header.component';
describe('Header Component', () => {
let $compile: ng.ICompileService;
let scope: ng.IRootScopeService;
let element: ng.IAugmentedJQuery;
beforeEach(angular.mock.module('weather'));
beforeEach(angular.mock.inject(function (_$compile_: ng.ICompileService, _$rootScope_: ng.IRootScopeService) {
$compile = _$compile_;
scope = _$rootScope_;
}));
beforeEach(() => {
element = $compile('<header-weather></header-weather>')(scope);
scope.$digest();
});
我不清楚如何访问控制器类,以测试组件的业务逻辑。我尝试注入 $componentController,但我不断收到错误“Uncaught TypeError: Cannot set property 'mock' of undefined”,我认为这与 angular-mocks 未正确注入有关。
任何人都可以建议一种解决方案或网站,在哪里可以找到有关使用 typescript 和 webpack 对 angular 1 组件进行单元测试的更多详细信息?
【问题讨论】:
标签: angularjs typescript webpack karma-jasmine angular-components