Mudanças entre as edições de "Unit testing with default Angular installation"

De Basef
Ir para: navegação, pesquisa
Linha 34: Linha 34:
 
</source>
 
</source>
  
 +
== Mocked Http Requests ==
 +
 +
1) Instead of using HttpClientModule, you should use HttpClientTestingModule. You will also use HttpTestingController. Below how to import and configure them:
 +
 +
<source lang="javascript">
 +
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
 +
 +
describe('YourClass', () => {
 +
 +
  beforeEach(() => {
 +
    TestBed.configureTestingModule({
 +
      imports:
 +
        ...
 +
        [ AppRoutingModule, HttpClientTestingModule ]
 +
        ...
 +
    });
 +
  });
 +
});
 +
</source>
  
  

Edição das 13h59min de 26 de abril de 2018


Getting instance of a service

let mockedLoginService = TestBed.get(LoginService);

Asserting that some method is called

let spySomeMethod = spyOn(someInstance, 'someMethod');
 
// do something here
 
expect(spySomeMethod).toHaveBeenCalled();

Asserting that some method is called with given arguments

let spySomeMethod = spyOn(someInstance, 'someMethod').and.callFake((arg1, arg2) => {
  expect(arg1).toEqual(10);
  expect(arg2).toEqual(20);
});
 
// do something here
 
expect(spySomeMethod).toHaveBeenCalled();

Mocked Http Requests

1) Instead of using HttpClientModule, you should use HttpClientTestingModule. You will also use HttpTestingController. Below how to import and configure them:

import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
 
describe('YourClass', () => {
 
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports:
        ...
        [ AppRoutingModule, HttpClientTestingModule ]
        ...
    });
  });
});