簡體   English   中英

如何在 Angular 6 中為 switch case 編寫單元測試用例?

[英]How to write unit test case for switch case in Angular 6?

我是為 Angular 6 編寫測試用例的新手,這是我的服務代碼。 如何為 switch case 編寫測試用例。 這個不知道怎么寫

import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {  headers: new HttpHeaders({ 'Content-Type': 'application/json' })};
const CUSTOMERS_URL = "http://localhost:8009/api/customers";
import * as sample1 from "./schema/schema-sample1.json";
import * as sample2 from "./schema/schema-sample2.json";
import * as sample3 from "./schema/schema-sample3.json";
import * as sample4 from "./schema/schema-sample4.json";
import * as sample5 from "./schema/schema-sample5.json";

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor() { }

   getDynamicRequestDetailsForApp(appName){
    switch(appName) {
      case "dcc": {
         return sample1;
         break;
      }
      case "sbr": {
         return sample2;
         break;
      }
      case "arc": {
         return sample3;
         break;
      }
      case "auth": {
         return sample5;
         break;
      }
      default: {
         return sample5;
         break;
      }
   }
  }
}

基本上switch是一個類似於if,else if, else的語句。 你可以假設case as else ifdefault as else 對於上面的代碼示例測試可能如下

describe('Service: FormService', () => {
beforeEach(() => {
    service = new AppService();
});
it('tests sbr', () => {
  expect(service.getDynamicRequestDetailsForApp('sbr')).toEqual(sample2);
});
it('tests dcc', () => {
  expect(service.getDynamicRequestDetailsForApp('dcc')).toEqual(sample1);
});
/* Same for remaining case statements with different function parameter */
});

這是一個Jasmin單元測試模型,當我們要測試組件的方法是否具有switch()條件時,一旦觸發,實際上是在default最后一個分支上輸入。
這樣我們就可以100%覆蓋單元測試覆蓋表的所​​有列 - 在StatementsBranchesFunctionsLines

describe(`'onTodoManipulation()' method: should`, () => {
    ...
    it()
    ...
    it(`console.error(), if arg.action !== 'update' && !== 'delete'` , () => {
        // --------------------------------------------------
        // Prepare it - it wasn't that easy!
        // --------------------------------------------------
        interface TodoObjToEdit {
            action: string;
            item: ItemWithId;
            propToUpdate: { [key: string]: string | boolean };
        }
        // tslint:disable-next-line: max-line-length
        const commonTodoItem: ItemWithId = { todo: 'TODO text', done: false, userId: 'someUserId123', autoID: 'I didn\'t made it!' };
        //
        //
        // 1) mock an arg, for thisComponent's 'onTodoManipulation()' Method,
        // where 'someDoneTodoUpdate.action' is NOT 'update', nor 'delete':
        const someDoneTodoUpdate: TodoObjToEdit = {
            action: 'this action is NOT "update" and is NOT "delete"',
            item: commonTodoItem,
            propToUpdate: { done: true}
        };
        // tslint:disable-next-line: max-line-length
        // 2) mock a 'mockedErrorFn' console.error, that will be triggered on the thisComponent's 'onTodoManipulation()' Method,
        // if, and only if, 'someDoneTodoUpdate.action' is NOT 'update', nor 'delete'
        let consoleOutput: string;
        const mockedErrorFn: {
            (...data: any[]): void;
            (message?: any, ...optionalParams: any[]): void;
        } = (output: string) => consoleOutput = output;
        console.error = mockedErrorFn;
        // --------------------------------------------------

        // Now we can trigger the thisComponent's Method we want to expect() something - a console.error trigger:
        thisComponent.onTodoManipulation(someDoneTodoUpdate);
        expect(consoleOutput).toContain('Please code it, first!');
        // and to reinforce this expect() is totally legit:
        expect(consoleOutput).not.toContain('Please codeXXX it, first!');

    });
});

而組件的TS file是:

public onTodoManipulation(todoManipulated: { action: string; item: ItemWithId; propToUpdate: { [key: string]: string | boolean } }) {

    switch (todoManipulated.action) {
        case 'update':
            // Call a Service... or any other action
            break;
        case 'delete':
            // Call a Service... or any other action
            break;

        default:
            console.error(
                `onTodoManipulation() ERROR: coming Action ("${todoManipulated.action}") is not known... Please code it, first!`
            );
            break;
    }
}

我希望它有幫助。

抱歉有點冗長,但通過復制和粘貼我所做的,在我簡單的Angular-Firebase TODO application ,我沒有花太多時間......

享受!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM