mercredi 19 septembre 2018

Angular testing: Testing a method with a type specific argument

I'm new to testing and I got into the following situation. My component has a method closeBox() that takes an argument of type Conversation. Conversation is a pretty complex model (see below). If I try to test this method by calling it with a simple object {id:1, name: 'me'}, it requests that it has to be an argument of type Conversation.

Now, I was wondering: Do I really have to fake an entire conversation object every time I want to test a method with a type-specific parameter? This conversation model is already a pain in the ass and it's not even that big. Surely there's a better way to do this. Anyone?

This is the test I am trying to perform: I make sure the fake conversation is present in the array property openConversations and then I call the closeBox method with a conversation as argument. as you can see it's a lot of work to create this fake conversation. Is there a better way to do this?

    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);

  });

Component method: this.openConversations is a property of this component. It's an array of Conversations

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

    }
  }

Conversation model

export class Conversation {

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

}

Aucun commentaire:

Enregistrer un commentaire