如何在Angular 2中使用自定义方法模拟对象?

时间:2016-10-07 00:35:01

标签: angular mocking

我想在Angular 2中为我的类定义添加自定义方法。但是当我尝试创建模拟对象时,我得到如下错误(参见Angular 2 Tour of Heroes教程)。

public/app/mock-searches.ts(3,14): error TS2322: Type '{ box: { x: number; y: number; width: number; height: number; }; dateCreated: Date; eventIdStr: s...' is not assignable to type 'Search[]'.
  Type '{ box: { x: number; y: number; width: number; height: number; }; dateCreated: Date; eventIdStr: s...' is not assignable to type 'Search'.
    Property 'refreshProducts' is missing in type '{ box: { x: number; y: number; width: number; height: number; }; dateCreated: Date; eventIdStr: s...'.
public/app/search.service.ts(33,40): error TS2304: Cannot find name 'err'.

refreshProducts(): void是为{I}尝试模拟的Search类声明的方法。我怎样才能最好地解决这个错误?或者我是否尝试向后做某些事情,这可能会在Angular 2中以更传统的方式处理?

search.ts(样本)

import { Rect } from './rect';

export class Search {
  box: Rect;
  dateCreated: Date;
  products: Product[];

  refreshProducts(): void {
    // Do something useful
  }
}

mock-searches.js(样本)

import { Search } from './search';

export const SEARCHES: Search[] = [
  { 
    box: { x: 4, y: 4, width: 20, height: 20 },
    dateCreated: new Date(),
    products: []
  }
];

1 个答案:

答案 0 :(得分:2)

如果您的对象文字不符合课程结构,那么您可以直接#34;施放"它(或者更准确地说是type assertion

export const SEARCHES: Search[] = [
  <Search> { 
    box: { x: 4, y: 4, width: 20, height: 20 },
    dateCreated: new Date(),
    products: []
  },
  <Search> { 
    box: { x: 4, y: 4, width: 20, height: 20 },
    dateCreated: new Date(),
    products: []
  }
];

您只需要确保使用模拟的任何内容,实际上并不需要使用模拟refreshProducts()的{​​{1}}方法

另见:

  • This post解释了一下TypeSript的结构类型系统