Skip to content

Commit

Permalink
test: add test cases for async and done
Browse files Browse the repository at this point in the history
  • Loading branch information
JiaLiPassion committed Jan 21, 2020
1 parent 85b791f commit 2620bd9
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 80 deletions.
38 changes: 27 additions & 11 deletions example/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import {
async,
fakeAsync,
tick,
ComponentFixture,
} from '@angular/core/testing';
import { async, fakeAsync, tick, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';

import { ConfigureFn, configureTests } from '@lib/testing';
Expand All @@ -20,7 +15,7 @@ describe('AppComponent', () => {
testBed.configureTestingModule({
declarations: [AppComponent],
imports: [NoopAnimationsModule],
schemas: [NO_ERRORS_SCHEMA],
schemas: [NO_ERRORS_SCHEMA]
});
};

Expand Down Expand Up @@ -50,8 +45,9 @@ describe('AppComponent', () => {
expect(compiled.querySelector('h1').textContent).toContain('app works!');
}));

it('looks async but is synchronous', <any>fakeAsync(
(): void => {
it(
'looks async but is synchronous',
<any>fakeAsync((): void => {
let flag = false;
setTimeout(() => {
flag = true;
Expand All @@ -61,8 +57,28 @@ describe('AppComponent', () => {
expect(flag).toBe(false);
tick(50);
expect(flag).toBe(true);
}
));
})
);

it(
'async should work',
<any>async((): void => {
let flag = false;
setTimeout(() => {
flag = true;
expect(flag).toBe(true);
}, 100);
})
);

it('test with done should work', (done): void => {
let flag = false;
setTimeout(() => {
flag = true;
expect(flag).toBe(true);
done();
}, 100);
});
});

test.todo('a sample todo');
112 changes: 43 additions & 69 deletions example/src/app/service/hero.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import {
HttpClientModule,
HttpErrorResponse,
HttpRequest
} from "@angular/common/http";
import {
HttpClientTestingModule,
HttpTestingController
} from "@angular/common/http/testing";
import { inject, TestBed } from "@angular/core/testing";

import { heroesUrl, HeroService } from "./hero.service";

describe("Service: HeroService", () => {
import { HttpClientModule, HttpErrorResponse, HttpRequest } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { inject, TestBed } from '@angular/core/testing';

import { heroesUrl, HeroService } from './hero.service';

describe('Service: HeroService', () => {
let service: HeroService;
let backend: HttpTestingController;

const expectedData = { id: 1, name: "Test hero" };
const expectedData = { id: 1, name: 'Test hero' };

const expectedDataAll = [
{ id: 1, name: "Test hero 1" },
{ id: 2, name: "Test hero 2" }
{ id: 1, name: 'Test hero 1' },
{ id: 2, name: 'Test hero 2' }
];

beforeEach(() => {
Expand All @@ -33,100 +26,81 @@ describe("Service: HeroService", () => {

// Mock implementation of console.error to
// return undefined to stop printing out to console log during test
jest.spyOn(console, "error").mockImplementation(() => undefined);
jest.spyOn(console, 'error').mockImplementation(() => undefined);
});

afterEach(inject(
[HttpTestingController],
(_backend: HttpTestingController) => {
_backend.verify();
}
));
afterEach(inject([HttpTestingController], (_backend: HttpTestingController) => {
_backend.verify();
}));

it("should create an instance successfully", () => {
it('should create an instance successfully', () => {
expect(service).toBeDefined();
});

it("should call the GET heroes api and return all results", () => {
it('should call the GET heroes api and return all results', () => {
let actualDataAll = {};

service.getHeroes().subscribe(data => (actualDataAll = data));

backend
.expectOne((req: HttpRequest<any>) => {
return req.url === `${heroesUrl}` && req.method === "GET";
return req.url === `${heroesUrl}` && req.method === 'GET';
}, `GET all hero data from ${heroesUrl}`)
.flush(expectedDataAll);

expect(actualDataAll).toEqual(expectedDataAll);
});

it("should call the GET hero api with id and return the result", () => {
it('should call the GET hero api with id and return the result', () => {
let actualData = {};

service.getHero(1).subscribe(data => (actualData = data));

backend
.expectOne((req: HttpRequest<any>) => {
return (
req.url === `${heroesUrl}` &&
req.method === "GET" &&
req.params.get("id") === "1"
);
return req.url === `${heroesUrl}` && req.method === 'GET' && req.params.get('id') === '1';
}, `GET hero data from ${heroesUrl}?id=1`)
.flush(expectedData);

expect(actualData).toEqual(expectedData);
});

test.each([
[1, { id: 1, name: "Test Hero 1" }],
[2, { id: 2, name: "Test Hero 2" }]
])(
"should call the GET hero api and return the result",
(id: number, testData: any) => {
debugger;
console.log(
"id, testData",
id,
testData,
(window as any).Zone.current.name
);
let actualData = {};

service.getHero(1).subscribe(data => (actualData = data));

backend
.expectOne((req: HttpRequest<any>) => {
return req.url === `${heroesUrl}` && req.method === "GET";
}, `GET hero data from ${heroesUrl}?id=${id}`)
.flush(testData);

expect(actualData).toEqual(testData);
}
);

it("should send an expected GET request and throw error to console when an error occurs", () => {
[1, { id: 1, name: 'Test Hero 1' }],
[2, { id: 2, name: 'Test Hero 2' }]
])('should call the GET hero api and return the result', (id: number, testData: any) => {
debugger;
console.log('id, testData', id, testData, (window as any).Zone.current.name);
let actualData = {};

service.getHero(1).subscribe(data => (actualData = data));

backend
.expectOne((req: HttpRequest<any>) => {
return req.url === `${heroesUrl}` && req.method === 'GET';
}, `GET hero data from ${heroesUrl}?id=${id}`)
.flush(testData);

expect(actualData).toEqual(testData);
});

it('should send an expected GET request and throw error to console when an error occurs', () => {
service.getHero(1).subscribe();

const getHeroRequest = backend.expectOne((req: HttpRequest<any>) => {
return (
req.url === `${heroesUrl}` &&
req.method === "GET" &&
req.params.get("id") === "1"
);
return req.url === `${heroesUrl}` && req.method === 'GET' && req.params.get('id') === '1';
}, `GET hero data from ${heroesUrl}?id=1`);

// Stimulate an error happens from the backend
getHeroRequest.error(new ErrorEvent("ERROR_GET_HERO_DATA"));
getHeroRequest.error(new ErrorEvent('ERROR_GET_HERO_DATA'));

expect(console.error).toHaveBeenCalled();
});

it("should return an observable of undefined and print error to console", () => {
it('should return an observable of undefined and print error to console', () => {
const result = service.handleError(
new HttpErrorResponse({ error: "Error occurs" }),
"test method"
new HttpErrorResponse({ error: 'Error occurs' }),
'test method'
);

expect(console.error).toHaveBeenCalled();
Expand Down

0 comments on commit 2620bd9

Please sign in to comment.