0

I have a component that has addTodo method and todos property, when addTodo is invoked I get all the todos from NGXS store and assign them to todos property

export class AppComponent {
  @Select("todo.todos") todos$!: Observable<Todo[]>;

  addTodo() {
    const todo = { title: "Todo title" };
    this.store
      .dispatch(new TodoActions.AddTodo(todo))
      .pipe(withLatestFrom(this.todos$))
      .subscribe(([_, todos]) => {
        this.todos = todos;
        console.log(this.todos); //(1)
      });
  }
}

Works fine in the browser, Now I want to write a unit test for this, Below is what I have currently

it("should #addTodo", (done) => {
  const todo = {title: "Todo title"};

  actions.pipe(ofActionCompleted(TodoActions.AddTodo)).subscribe(() => {
    console.log(component.todos); //(2)
    expect(component.todos).toBe(todo); //Assertion fails
    done();
  });

  component.addTodo();
});

log (2) prints first and gives undefined, then log (1) gets printed which means data is assigned later after the assertion, How to test this scenario?

Sameer
  • 4,758
  • 3
  • 20
  • 41

1 Answers1

0

Answering my own question, It was fairly simple

I was confused by the Documentation to use actions, but not needed.

it('should #addTodo', () => {
  /** Make sure to mock the service **/

  const todo = [{ title: 'Todo title' }];

  component.addTodo();

  expect(component.todos).toEqual(todo); //passed
});

BTW I am using jest

Sameer
  • 4,758
  • 3
  • 20
  • 41