亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 jasmine 模擬 if/else 語句 - 使用 Angular/Typescript

使用 jasmine 模擬 if/else 語句 - 使用 Angular/Typescript

智慧大石 2023-07-06 17:49:46
我在現有函數中添加了一個小修改。我們的質量檢查已將其識別為新代碼,因此我需要用單元測試覆蓋新的 4 行 - 記住,一開始就沒有單元測試,而且我添加的函數非常大!我嘗試了多種方法來嘗試模擬服務、變量、間諜活動等……但總是出錯。我對茉莉花很陌生,所以很掙扎。我需要做的就是進行任何類型的檢查以覆蓋真值/假值。組件.ts 文件hasDescription() {        return this.isBrilliant() || this.isCool();    }isBrilliant() {        return this.service.Type.description == 'Brilliant';    }isCool() {        return this.service.Type.description == 'Cool';    }onExportToExcel(): void {        var r = [];        // added the below if/else - any check on this will be suffice.        if (this.hasDescription()) {            if (!this.isBrilliant()) {                r.push('This is Cool');            } else {                r.push('This is Brilliant');            }            if (!this.isBrilliant()) {            r.push('More Cool content');            }        }}我嘗試將isBrilliant() 設置為模擬值true,并期望該值是真實的expect(component.isBrilliant()).toBeTruthy();我嘗試通過以下方式在規范文件中設置它:const isBrilliant = true;component.isBrilliant = isBrilliant;然而我在這里得到的錯誤是Type 'true' is not assignable to type '() => boolean'.如果任何經驗豐富的 jasmine 開發人員可以向我展示一種快速方法來覆蓋這個簡單的聲明,我將不勝感激。謝謝
查看完整描述

1 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

作為最佳實踐的一部分,我建議進行一些更改。

  1. 不要模擬組件方法,因為您需要測試它們。在您的情況下,您應該設置 value?this.service.Type.description,因此它應該返回trueor?false。這將是一個正確的做法。

如果this.service是已注入的服務construtor,則可以模擬該服務。

  1. 由于您正在使用 測試多個條件if?else,因此您需要編寫幾個it塊才能獲得良好的測試覆蓋率。

  2. 要進行測試var r,您應該將其聲明public為組件級別的變量,而不是在function.?let也更喜歡var.

這是一個示例代碼,您可以編寫該代碼來設置其中的值isBrilliant()

it('should push Brilliant when the Description is so,()=>{

? ?component.service.Type.description = 'Brilliant';

? ?component.onExportToExcel();

? ?expect(component.r.length).toBe(1);

? ?expect(component.r[0]).toBe('This is Brilliant');

})


it('should push other cool content when the Description is not Brilliant,()=>{

? ?component.service.Type.description = 'something else';

? ?component.onExportToExcel();

? ?expect(component.r.length).toBe(2);

? ?// check other values in expect block accordingly

})


// you should also check that "component.r" has zero length when hasDescription() returns false


我希望上面的代碼片段能給你一個好的開始


查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號