Angular 分量测试错误: TypeError Cannot read property 'subscribe' of undefined

标签 angular unit-testing jasmine angular-test

我有一个简单的单元测试,是在 Angular 6 组件上使用 karma/jasmine 完成的。从我收集的pluralsight类(class)和文档来看,我似乎正在正确地模拟我的组件所需的服务,但是当调用该方法以从模拟服务返回数据时,我收到错误消息,指出属性订阅未定义。

我的“it”函数是空的,因为一旦在 beforeEach 方法中构造了组件,测试就会失败。组件的构造函数调用我尝试测试的方法。请参阅下面我的代码。

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MainComponent } from './main.component';
import { DataService } from '../services/data.service';
import { of } from 'rxjs';
import { NO_ERRORS_SCHEMA } from "@angular/core";

describe('Should construct MainComponent', () => {
	let mainComponent: MainComponent;
	let EMPLOYEES;
	let fixture: ComponentFixture<MainComponent>;
	let mockDataService;

	beforeEach(() => {
		EMPLOYEES = [
			{
				"PrismEmployeeID": 1,
				"FirstName": "install2",
				"LastName": "account",
				"Initials": "IA ",
				"NickName": "",
				"SSN": "",
				"DateOfBirth": "09/26/2014",
				"HireDate": "09/26/2014",
				"OfficePhone": "9043943239",
				"OfficeFax": "9042246400",
				"ClassificationID": 133,
				"ClassificationDescription": "Claims Support U.S. Insurance",
				"SupervisorID": 32,
				"DepartmentID": 2,
				"DepartmentDescription": "Information Technology",
				"SupervisorName": "Jerry Sutton",
				"CountryID": 1,
				"CountryName": "United States"
			}
		];

		mockDataService = jasmine.createSpyObj(['GetEmployees']);

		TestBed.configureTestingModule({
			declarations: [MainComponent],
			providers: [{ provide: DataService, useValue: mockDataService }],
			schemas: [NO_ERRORS_SCHEMA]
		});

		fixture = TestBed.createComponent(MainComponent);
		fixture.detectChanges();

		mockDataService = jasmine.createSpyObj(['GetEmployees']);
	});

	it('should get an array Employees',
		() => {});
});

主要组件

import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { DataService } from '../services/data.service';
import { TableComponent } from './table/table.component';

@Component({
	selector: 'main',
	templateUrl: './main.component.html',
	styleUrls: ['./main.component.css']
})
export class MainComponent {
	columns: string[] = ['PrismEmployeeID', 'LastName', 'FirstName', 'Initials', 'LastFour', 'BirthDate', 'HireDate', 'OfficePhone', 'OfficeFax', 'ClassificationDescription', 'SupervisorName', 'DepartmentDescription', 'CountryName'];
	loading: boolean = false;
	@Input() tableData: Employee[];

	constructor(private _dataService: DataService) {
		this.loadEmployees();
	}

	loadEmployees() {
		this.loading = true;
		this._dataService.GetEmployees().subscribe((data) => {
			this.loading = false;
			this.tableData = data.json() as Employee[];
		});
	}

	onLoading(loading: boolean) {
		this.loading = loading;
	}

	onReloadData(reloadData: boolean) {
		this.loadEmployees();
	}
}

interface Employee {
	PrismEmployeeID: number;
	FirstName: string;
	LastName: string;
	Initials: string;
	NickName: string;
	SSN: string;
	DateOfBirth: string;
	HireDate: string;
	OfficePhone: string;
	OfficeFax: string;
	ClassificationID: number;
	ClassificationDescription: string;
	SupervisorID: number;
	DepartmentID: number;
	DepartmentDescription: string;
	SupervisorName: string;
	CountryID: number;
	CountryName: string;

	_selected: boolean;
}

<br/>
<h2>Prism Employees</h2>
<div *ngIf="loading" class="d-flex justify-content-center bd-highlight mb-3">
	<div class="p-2 bd-highlight"></div>
	<div class="p-2 bd-highlight">
		<mat-spinner id="overlay"></mat-spinner>
	</div>
	<div class="p-2 bd-highlight"></div>
</div>

<div *ngIf='tableData'>
  <table-component #table (loading)="onLoading($event)" (reloadData)="onReloadData($event)" [data]="tableData" [displayedColumns]="columns"></table-component>
</div>

最佳答案

问题是您当前提供的服务 stub 没有为 GetEmployees 方法配置返回。这意味着一旦组件调用前一个函数并订阅其(未定义)返回,它将触发异常。

要解决这个问题,您需要伪造该方法的返回值。基于this answer你可以尝试如下:

import {of} from 'rxjs';
...
mockDataService = jasmine.createSpyObj(DataService.Name, {'GetEmployees': of(EMPLOYEES)});
...

更新:

为了使其正常工作,您必须重构 DataService.GetEmployees 方法以具有以下签名:

GetEmployees(): Observable<Employee[]>;

DataService.GetEmployees 的当前实现是 leaky abstraction ,因为它从旧的 Http API 返回原始的 Response 对象,迫使使用者(在本例中为组件)了解有关底层实现的详细信息(此详细信息是使用 data.json() 作为 Employee[])

关于 Angular 分量测试错误: TypeError Cannot read property 'subscribe' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53118269/

相关文章:

Angular 从 REST API 获取图片并显示它

angular - [at-loader] node_modules\@types\jasmine 中的错误

c - 嵌套预处理器指令或其他技巧以有条件地重新定义 static 关键字

javascript - 为什么 Jasmine 在监视 $.ajax 时不重置 spy ?

javascript - 如何使用 jasmine.js 测试控制台输出?

angularjs - Angular6 ngStyle 动态应用样式

javascript - Angular,如何在多个页面而不是在一个大列表中显示 *ngFor

c# - 使用最小起订量的扩展方法的单元测试

c# - 我如何对 Windsor 可以解析 Asp.net MVC3 Controller 依赖项进行单元测试?

angularjs - angular.factory 的单元测试是什么以及如何进行