typescript Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming/angular-2/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming/angular-2/相关的知识,希望对你有一定的参考价值。

import {
  beforeEachProviders,
  describe,
  expect,
  inject,
  it,
} from '@angular/core/testing';
import { 
  ComponentFixture, 
  TestComponentBuilder,
} from '@angular/compiler/testing';
import { ROUTER_FAKE_PROVIDERS } from '@angular/router/testing';
import { App } from './app';

import { setBaseTestProviders } from '@angular/core/testing';
import {
  TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
  TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
} from '@angular/platform-browser-dynamic/testing';

setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);

describe('App', () => {

  beforeEachProviders(() => [ROUTER_FAKE_PROVIDERS])

  it('should be able to test', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb.createAsync(App).then(componentFixture => {
      componentFixture.detectChanges();
      expect(true).toBe(true);
    });
  }));

});
// App
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class TestService {
  constructor(private http: Http) {}

  getUsers() {
    return this.http.get('http://foo.bar');
  }
}


// App tests
import {
  beforeEach,
  beforeEachProviders,
  describe,
  expect,
  inject,
  it,
} from '@angular/core/testing';

import { provide } from '@angular/core';
import { BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

describe('Http', () => {

  beforeEachProviders(() => [
    TestService,
    BaseRequestOptions,
    MockBackend,
    provide(Http, {
      useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    })
  ]);

  beforeEach(inject([MockBackend], (backend: MockBackend) => {
    const baseResponse = new Response(new ResponseOptions({ body: 'got response' }));
    backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
  }));

  it('should return response when subscribed to getUsers',
    inject([TestService], (testService: TestService) => {
      testService.getUsers().subscribe((res: Response) => {
        expect(res.text()).toBe('got response');
      });
    })
  );

})
// App
class TestService {
  public name: string = 'Injected Service';
}


// App tests
import {
  it,
  describe,
  expect,
  inject,
  beforeEachProviders,
} from '@angular/core/testing';

import { provide } from '@angular/core';
import { setBaseTestProviders } from '@angular/core/testing';
import {
  TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
  TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
} from '@angular/platform-browser-dynamic/testing';

setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);


describe('TestService', () => {

  beforeEach(() => {
    this.testService = new TestService();
  });

  it('should have name property set', () => {
    expect(this.testService.name).toBe('Injected Service');
  });

});


describe('TestService Injected', () => {

  beforeEachProviders(() => [TestService]);

  it('should have name property set', inject([TestService], (testService: TestService) => {
    expect(testService.name).toBe('Injected Service');
  }));

});


class MockTestService {
  public mockName: string = 'Mocked Service';
}

describe('TestService Mocked', () => {

  beforeEachProviders(() => [
    provide(TestService, {useClass: MockTestService})
  ]);

  it('should have name property set', inject([TestService], (testService: TestService) => {
    expect(testService.mockName).toBe('Mocked Service');
  }));

});


class MockTestServiceInherited extends TestService {
  public sayHello(): string {
    return this.name;
  }
}

describe('TestService Mocked Inherited', () => {

  beforeEachProviders(() => [
    provide(TestService, { useClass: MockTestServiceInherited })
  ]);

  it('should say hello with name', inject([TestService], (testService: TestService) => {
    expect(testService.sayHello()).toBe('Injected Service');
  }));

});
// App
import { Component, Input } from '@angular/core';
import { NgFor } from '@angular/common';

@Component({
  selector: 'list',
  template: '<span *ngFor="let user of users">{{ user }}</span>',
  directives: [NgFor],
})
export class ListComponent {
  @Input() public users: Array<string> = [];
}


// App tests
import {
  async,
  it,
  describe,
  expect,
  inject,
  beforeEach,
  beforeEachProviders,
} from '@angular/core/testing';

import {
  ComponentFixture,
  TestComponentBuilder,
} from '@angular/compiler/testing'

import { setBaseTestProviders } from '@angular/core/testing';
import {
  TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
  TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
} from '@angular/platform-browser-dynamic/testing';

setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);


describe('ListComponent', () => {

  it('should render list', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb.createAsync(ListComponent).then(componentFixture => {
      const element = componentFixture.nativeElement;
      componentFixture.componentInstance.users = ['John'];
      componentFixture.detectChanges();
      expect(element.querySelectorAll('span').length).toBe(1);
    });
  }));

});



// App DI
class UserService {
  public users: Array<string> = ['John'];
}

@Component({
  selector: 'list',
  template: '<span *ngFor="let user of users">{{ user }}</span>',
  directives: [NgFor],
})
class ListComponentBootstrapDI {
  private users: Array<string> = [];

  constructor(userService: UserService) {
    this.users = userService.users;
  }
}


// App DI tests
import { provide } from '@angular/core';

class MockUserService {
  public users: Array<string> = ['John', 'Steve'];
}

describe('ListComponent DI', () => {

  beforeEachProviders(() => [
    provide(UserService, { useClass: MockUserService })
  ]);

  it('should render list', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb.createAsync(ListComponentBootstrapDI).then(componentFixture => {
      const element = componentFixture.nativeElement;
      componentFixture.detectChanges();
      expect(element.querySelectorAll('span').length).toBe(2);
    });
  }));

});


// App DI for Component
@Component({
  selector: 'list',
  template: '<span *ngFor="let user of users">{{ user }}</span>',
  directives: [NgFor],
  providers: [UserService],
})
class ListComponentComponentDI {
  private users: Array<string> = [];

  constructor(userService: UserService) {
    this.users = userService.users;
  }
}

// App DI for Component tests
describe('ListComponent DI Component', () => {
  it('should render list', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb
      .overrideProviders(
        ListComponentComponentDI,
        [provide(UserService, { useClass: MockUserService })]
      )
      .createAsync(ListComponentComponentDI).then(componentFixture => {
      const element = componentFixture.nativeElement;
      componentFixture.detectChanges();
      expect(element.querySelectorAll('span').length).toBe(2);
    });
  }));
});



// App final test
describe('ListComponent Final', () => {

  beforeEach(async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb
      .overrideProviders(
        ListComponentComponentDI,
        [provide(UserService, { useClass: MockUserService })]
      )
      .createAsync(ListComponentComponentDI)
      .then(componentFixture => {
        this.listComponentFixture = componentFixture;
      });
  })));

  it('should render list', () => {
    const element = this.listComponentFixture.nativeElement;
    this.listComponentFixture.detectChanges();
    expect(element.querySelectorAll('span').length).toBe(2);
  });

});
// App
import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<span>{{ sayHello() }}</span>',
})
export class App {
  public name: string = 'John';

  sayHello(): string {
    return `Hello ${this.name}`;
  }
}


// App tests

describe('App', () => {

  beforeEach(() => {
    this.app = new App();
  });

  it('should have name property', () => {
    expect(this.app.name).toBe('John');
  });

  it('should say hello with name property', () => {
    expect(this.app.sayHello()).toBe('Hello John');
  });

});

以上是关于typescript Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming/angular-2/的主要内容,如果未能解决你的问题,请参考以下文章

typescript Angular最终版本的Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming

typescript Angular最终版本的Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming

typescript Angular 2+ Jasmine测试规格样板

通过 Webpack(终端)执行 Typescript Jasmine 测试以测试 Angular2

Angular2(TypeScript)中的单元测试/模拟窗口属性

如何使用 Jasmine 为私有方法编写 Angular / TypeScript 单元测试