Andy
Andy

Reputation: 205

rxjs throw jasmine test issue

I'm really new to Jasmine and I'm trying to figure out what I'm doing wrong. Currently I'm trying to write a test where the error message from the component instance matches the variable error, but it's failing. I'm passing the variable to the error throw so it should pass I would think. I appreciate any help.

Error: TodosComponent should set the message property if server returned an error when adding a new todo FAILED

import { TodosComponent } from './todos.component';
import { TodoService } from './todo.service';
import { from, empty, throwError } from "rxjs";

describe('TodosComponent', () => {
  let component: TodosComponent;
  let service: TodoService;
  beforeEach(() => {
    service = new TodoService(null);
    component = new TodosComponent(service);
  });

  it('should set the message property if server returned an error when adding a new todo', () => {
    let error = 'error from the server';
    let spy = spyOn(service, 'add').and.returnValue(throwError(new Error(error)));
    component.add();
    expect(component.message).toBe(error);

  });
});

todo.component.ts


import { TodoService } from './todo.service'

export class TodosComponent {
  todos: any[] = [];
  message;

  constructor(private service: TodoService) { }

  ngOnInit() {
    this.service.getTodos().subscribe(t => this.todos = t);
  }

  add() {
    var newTodo = { title: '... ' };
    this.service.add(newTodo).subscribe(
      t => this.todos.push(t),
      err => this.message = err);
  }

  delete(id) {
    if (confirm('Are you sure?'))
      this.service.delete(id).subscribe();
  }
}

Upvotes: 0

Views: 108

Answers (1)

yurzui
yurzui

Reputation: 214007

Looks like you're matching different values.

If you want component.message to be a string then you need to throw string not Error object:

let spy = spyOn(service, 'add').and.returnValue(throwError(new Error(error)));
                                                                 ||
                                                                 \/
                                                     throwError(error)

Otherwise you need to compare message with that new Error.

The complete test case is:

it('should set the message property if server returned an error when adding a new todo', () => {
  let error = 'error from the server';
  let spy = spyOn(service, 'add').and.returnValue(throwError(error));
  component.add();
  expect(component.message).toBe(error);
});

Upvotes: 1

Related Questions