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

De Basef
Ir para: navegação, pesquisa
 
(13 revisões intermediárias pelo mesmo usuário não estão sendo mostradas)
Linha 1: Linha 1:
  
 +
 +
== Asserting that a value is equal to something ==
 +
 +
<source lang="javascript">
 +
 +
expect(someVariable).toEqual('something');
 +
 +
</source>
 +
 +
== Asserting that a value is defined ==
 +
 +
<source lang="javascript">
 +
 +
expect(someVariable).toBeDefined();
 +
 +
</source>
 +
 +
== Asserting that a value is true ==
 +
 +
<source lang="javascript">
 +
 +
expect(someVariable).toBeTruthy();
 +
 +
</source>
 +
 +
== Asserting that a value is false ==
 +
 +
<source lang="javascript">
 +
 +
expect(someVariable).toBeFalsy();
 +
 +
</source>
  
 
== Getting instance of a service ==
 
== Getting instance of a service ==
  
 
<source lang="javascript">
 
<source lang="javascript">
let mockedLoginService = TestBed.get(LoginService);
+
let mockedService = TestBed.get(YourService);
 +
</source>
 +
 
 +
== Simple test structure ==
 +
 
 +
<source lang="javascript">
 +
  it('should be created', () => {
 +
    expect(component).toBeTruthy();
 +
  });
 +
</source>
 +
 
 +
== Injecting a service into a test ==
 +
 
 +
<source lang="javascript">
 +
  it('your test', inject([YourService], (service: YourService) => {
 +
   
 +
  }));
 
</source>
 
</source>
  
Linha 36: Linha 84:
 
== Mocked Http Requests ==
 
== Mocked Http Requests ==
  
1) Instead of using HttpClientModule, you should use HttpClientTestingModule. You will also use HttpTestingController. Below how to import and configure them:
+
1) Instead of using '''HttpClientModule''', you should use '''HttpClientTestingModule'''. You will also use '''HttpTestingController'''. Below how to import and configure them:
  
 
<source lang="javascript">
 
<source lang="javascript">
Linha 57: Linha 105:
 
</source>
 
</source>
  
 +
2) In your test you need to get an instance of '''HttpTestingController''':
  
 +
<source lang="javascript">
 +
  ...
 +
  it('your test', () => {
 +
 +
    let httpMock = TestBed.get(HttpTestingController);
 +
 +
  });
 +
  ...
 +
</source>
 +
 +
3) In the same test you should assert that a call has been made with:
 +
 +
<source lang="javascript">
 +
    let mockedResponse = {
 +
        statusCode: 200,
 +
        body: {
 +
            anything: 'your endpoint returns'
 +
        }
 +
    }
 +
 +
    const request = httpMock.expectOne('http://some.request.url/to/somewhere');
 +
 +
    request.flush(mockedResponse);
 +
    httpMock.verify();
 +
</source>
 +
 +
== Expecting that a method is called X times ==
 +
 +
<source lang="javascript">
 +
    let spySomeMethod = spyOn(someInstance, 'someMethod');
 +
 +
    // do something here
 +
 +
    expect(spySomeMethod.calls.count()).toEqual(2);
 +
 +
</source>
 +
 +
== Executing code prior to each test ==
 +
 +
<source lang="javascript">
 +
  beforeEach(() => {
 +
    // do your code here
 +
  });
 +
</source>
 +
 +
== Dependencies configuration ==
 +
 +
<source lang="javascript">
 +
describe('YourComponent', () => {
 +
  let component: YourComponent;
 +
  let fixture: ComponentFixture<YourComponent>;
 +
 +
  beforeEach(async(() => {
 +
    TestBed.configureTestingModule({
 +
      declarations:
 +
        [  ],
 +
      imports:
 +
        [  ],
 +
      providers:
 +
        [  ]
 +
    })
 +
    .compileComponents();
 +
  }));
 +
 +
  beforeEach(() => {
 +
    fixture = TestBed.createComponent(YourComponent);
 +
    component = fixture.componentInstance;
 +
    fixture.detectChanges();
 +
  });
 +
  ...
 +
})
 +
</source>
 +
 +
 +
== Testing if a html tag and content exists ==
 +
 +
<source lang="javascript">
 +
  it('should render title in a h1 tag', async(() => {
 +
    const fixture = TestBed.createComponent(AppComponent);
 +
    fixture.detectChanges();
 +
    const compiled = fixture.debugElement.nativeElement;
 +
    expect(compiled.querySelector('h1').textContent).toContain('Website title');
 +
  }));
 +
</source>
  
  
[[Category: AngularJS2]]
+
[[Category: Angular]]

Edição atual tal como às 09h39min de 27 de janeiro de 2020


Asserting that a value is equal to something

expect(someVariable).toEqual('something');

Asserting that a value is defined

expect(someVariable).toBeDefined();

Asserting that a value is true

expect(someVariable).toBeTruthy();

Asserting that a value is false

expect(someVariable).toBeFalsy();

Getting instance of a service

let mockedService = TestBed.get(YourService);

Simple test structure

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

Injecting a service into a test

  it('your test', inject([YourService], (service: YourService) => {
 
  }));

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 ]
        ...
    });
  });
  ...
});

2) In your test you need to get an instance of HttpTestingController:

  ...
  it('your test', () => {
 
    let httpMock = TestBed.get(HttpTestingController);
 
  });
  ...

3) In the same test you should assert that a call has been made with:

    let mockedResponse = {
        statusCode: 200,
        body: {
            anything: 'your endpoint returns'
        }
    }
 
    const request = httpMock.expectOne('http://some.request.url/to/somewhere');
 
    request.flush(mockedResponse);
    httpMock.verify();

Expecting that a method is called X times

    let spySomeMethod = spyOn(someInstance, 'someMethod');
 
    // do something here
 
    expect(spySomeMethod.calls.count()).toEqual(2);

Executing code prior to each test

  beforeEach(() => {
    // do your code here
  });

Dependencies configuration

describe('YourComponent', () => {
  let component: YourComponent;
  let fixture: ComponentFixture<YourComponent>;
 
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations:
        [  ],
      imports:
        [  ],
      providers:
        [  ]
    })
    .compileComponents();
  }));
 
  beforeEach(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  ...
})


Testing if a html tag and content exists

  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Website title');
  }));