我是Angular 2和Karma + Jasmine单元测试的新手。我无法弄清楚我为了使这个单元测试使用模拟响应而产生的语义错误。在控制台中,当“expect(items [0] .itemId).toBe(2);”时运行时,它表示项目[0] .itemId未定义。
有人能够帮助我或指出我正确的方向吗?如果您需要任何其他信息,请与我们联系。谢谢!
item.ts
private static void getAllFilesAndFoldersInPath(TreeView treeView, string path)
{
treeView.Items.Clear();
var stack = new Stack<TreeViewItem>();
var rootDirectory = new DirectoryInfo(path);
TreeViewItem node = new TreeViewItem();
node.Header = rootDirectory;
stack.Push(node);
while (stack.Count > 0)
{
var currentNode = stack.Pop();
var directoryInfo = (DirectoryInfo)currentNode.Header;
try
{
foreach (var directory in directoryInfo.GetDirectories())
{
if (!directory.Name.StartsWith("$"))
{
TreeViewItem childDirectoryNode = new TreeViewItem();
childDirectoryNode.Header = directory;
currentNode.Items.Add(childDirectoryNode);
stack.Push(childDirectoryNode);
}
}
foreach (var file in directoryInfo.GetFiles())
{
if (System.IO.Path.GetFileName(file.Name).StartsWith("~$") || System.IO.Path.GetExtension(file.Name) == ".tmp")
{
continue;
}
TreeViewItem tempNode = new TreeViewItem();
tempNode.Header = file;
currentNode.Items.Add(tempNode);
}
}
catch (UnauthorizedAccessException e) { }
}
treeView.Items.Add(node);
}
item.service.ts
export class Item {
itemId: number;
itemName: string;
itemDescription: string;
}
item.service.spec.ts
import { Injectable, Inject } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Item } from './item';
@Injectable()
export class ItemService {
private headers = new Headers({'Content-Type': 'application/json'});
constructor(
private http: Http)
{
}
getItems(listOptions: Object): Observable<Item[]> {
return this.http.post('/listItems', listOptions, {headers:this.headers})
.map(response => response.json() as Item[])
}
}
Plunkr:https://plnkr.co/edit/m7In2eVh6oXu8VNYFf9l?p=preview (Plunkr也有一些错误我需要帮助,但主要文件都在那里)
答案 0 :(得分:0)
mockResponse主体与实际响应主体不匹配,这就是我收到错误的原因。
mockResponse = new Response(new ResponseOptions({body: {data: items}, status: 200}));
应为mockResponse = new Response(new ResponseOptions({body: items, status: 200}));