Verifying Methods and Properties

We can test the properties and methods of simple Angular components fairly easily - after all, Angular components are simple classes that we can create and interface with. Say we had a simple component that kept a defined message displayed. The contents of the message may be changed through the setMessage function, and the clearMessage function would put an empty message in place. This is a very trivial component but how would we test it?

message.component.ts

  1. import {Component} from '@angular/core';
  2. @Component({
  3. selector: 'display-message',
  4. template: '<h1>{{message}}</h1>'
  5. })
  6. export class MessageComponent {
  7. public message: string = '';
  8. constructor() {}
  9. setMessage(newMessage: string) {
  10. this.message = newMessage;
  11. }
  12. clearMessage() {
  13. this.message = '';
  14. }
  15. }

Now for our unit test. We'll create two tests, one to test the setMessage function to see if the new message shows up and another to test the clearMessage function to see if clearing the message works as expected.

message.spec.ts

  1. import {MessageComponent} from './message.component';
  2. describe('Testing message state in message.component', () => {
  3. let app: MessageComponent;
  4. beforeEach(() => {
  5. app = new MessageComponent();
  6. });
  7. it('should set new message', () => {
  8. app.setMessage('Testing');
  9. expect(app.message).toBe('Testing');
  10. });
  11. it('should clear message', () => {
  12. app.clearMessage();
  13. expect(app.message).toBe('');
  14. });
  15. });

View Example

We have created two tests: one for setMessage and the other for clearMessage. In order to call those functions we must first initialize the MessageComponent class. This is accomplished by calling the beforeEach function before each test is performed.

Once our MessageComponent object is created we can call setMessage and clearMessage and analyze the results of those actions. We formulate an expected result, and then test to see if the result we were expecting came to be. Here we are testing whether or not the message we tried to set modified the MessageComponent property message to the value we intended. If it did, then the test was successful and our MessageComponent works as expected.

原文: https://angular-2-training-book.rangle.io/handout/testing/components/verify.html