Justin
Justin

Reputation: 887

Mock Angular 4+ service error

I've created a mock service for my test but I want to test what happens, just in one test, when an error occurs and the consequences of that error. In Java when I use mock services I can have, for a particular test method the mock service return an error by using when(mockservice.method).thenReturn(error) and I'm unsure how to do the equivalent in Jasmine. Here's what I have so far:

class MockManagerService {
  @Output()
  selectedEventObject: EventEmitter<any> = new EventEmitter();

  getAlertsAndMessagesData(): Observable<any> {
  const data = {alerts: ''};
  return Observable.of(data);
  }
}

describe('DataComponent', () => {
  let component: DataComponent;
  let fixture: ComponentFixture<DataComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ DataComponent ],
  imports: [DataTableModule, HttpClientModule],
  providers: [
    {
        provide: ManagerService,
        useClass: MockManagerService
    }
  ]
})
.compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(DataComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should be created', () => {
expect(component).toBeTruthy();
});
});

The section of the ManagerService code I want to test is this:

err => {
        this.managerService.processError(err);
        this.managerService.userLoggedIn.emit(false);
    });

I don't need to test if the .processError method does what it does but I would like to see if the event is emitted.

Is there some way to do this:

it('should process error', () => {
  // Java psuedo code to explain what I want to do in JavaScript
  when(MockManagerService.methodThatThrowsError).thenReturn(error);
  verify(event emitted to userLoggedIn emitter)
}

Upvotes: 1

Views: 1129

Answers (1)

user4676340
user4676340

Reputation:

Start by importing the testing module of the Http client :

import { 
  HttpClientTestingModule, 
  HttpTestingController // We'll need it
} from '@angular/common/http/testing';


imports: [HttpClientTestingModule],

Then, in your tests (or your before each), get the http controller like so

const httpMock = TestBed.get(HttpTestingController); 

now, you can simply mock a response or an error like so

myService.myMethod().subscribe(
  data => {/* expects */}
  err => {/* expects */}
);
const request = httpMock.expectOne(service.URL + 'your_url');
// make your expectations about the request here
expect(request.request.method).toEqual('GET');
// use either of them in a test, not both ! 
// -----------------------------
request.flush(/* data to return in success */);
request.error(new ErrorEvent('error string here');
// -----------------------------
httpMock.verify();

Upvotes: 2

Related Questions