首页 > 解决方案 > 角度测试:使用特定类型的参数测试方法

问题描述

我是测试新手,我遇到了以下情况。我的组件有一个closeBox()采用 type 参数的方法ConversationConversation是一个非常复杂的模型(见下文)。如果我尝试通过使用简单对象 {id:1, name: 'me'} 调用它来测试此方法,它会要求它必须是 type 的参数Conversation

现在,我想知道:每次我想用特定类型的参数测试方法时,我真的必须伪造整个对话对象吗?这种对话模型已经很麻烦了,而且还没有那么大。当然有更好的方法来做到这一点。任何人?

这是我要执行的测试:我确保数组属性中存在虚假对话openConversations,然后我调用 closeBox 方法,并将对话作为参数。如您所见,创建这种虚假对话需要做很多工作。有一个更好的方法吗?

    it('should close the chatbox', function () {
    const mockConversation = new Conversation(
      [{id: 'jos'}],
      {username: 'jos', profilePicture: {name: 'jos', uploaded: true, userId: '12345'}},
      '123456',
      '123457',
      '9875412');
    component.openConversations = [mockConversation];

    fixture.detectChanges();

    component.closeBox(mockConversation);

    expect(component.openConversations).toBe(null);

  });

组件方法:this.openConversations 是该组件的一个属性。这是一系列对话

closeBox(openConv: Conversation) {
    const index = this.openConversations.indexOf(openConv);
    if (index > -1) {
      this.openConversations.splice(index, 1);

    }
  }

对话模式

导出类对话{

  constructor(
    public messages: Array<{}>,
    public otherUser: {
      username: string,
      profilePicture: {
        name: string,
        uploaded: boolean,
        userId: string
      }},
    public user1: string,
    public user2: string,
    public _id: string
  ) {}

}

标签: angularunit-testingtestingjasmine

解决方案


推荐阅读