![](/img/trans.png)
[英]Test PhantomJS Array.prototype.includes() in Angular 7
[英]Jest test failing when using Array.prototype.includes with Typescript?
我開始在這個項目中使用 Array.prototype.includes:
https://github.com/fireflysemantics/validator
使用Angular Package格式打包,源碼在這個目錄下:
https://github.com/fireflysemantics/validator/tree/master/projects/validator
該項目構建良好,但是在運行 Jest 測試時會發生此錯誤:
FAIL projects/validator/src/lib/decorators/IsDefined.spec.ts
● should create an error when using validate
TypeError: Cannot read property 'includes' of undefined
35 | const mc: MetaClass = ValidationContainer.metaClasses.get(cn);
36 | if (mc) {
> 37 | const properties: string[] = mc.properties.filter(p => !exlude.includes(p))
所以似乎 Jest 沒有選擇屬性 typescript 配置,其中包括:
"lib": [
"dom",
"es2018"
]
想法?
您誤解了錯誤。 並不是不允許includes
。
這是它無法訪問屬性includes
的值undefined
,即顯然您嘗試執行undefined.includes
,因此這意味着exlude
必須是undefined
。
在您的IsDefined.spec.ts
中,您調用validate
如下:
it(`should create an error when using validate`, ()=>{
let IDI = new IsDefinedInvalid();
let e = validate(IDI);
expect(e.valid).toBeFalsy();
});
因此,您只傳遞了 1 個參數 ( IDI
) 來validate
。 但是,在validate.ts
中,您可以像這樣定義 function:
export function validate(target: any, exlude?: string[]): ObjectErrors {
let oes: ObjectErrors = new ObjectErrors();
const cn: string = target.constructor.name;
const mc: MetaClass = ValidationContainer.metaClasses.get(cn);
if (mc) {
const properties: string[] = mc.properties.filter(p => !exlude.includes(p))
properties.forEach(p => {
if (!validateProperty(target, p, oes)) {
oes.valid = false;
}
});
}
return oes;
}
如您所見, validate
需要兩個arguments - target
和exlude
。 (順便說一句,這是拼寫錯誤,應該用c
exclude
。)是的, exlude
標記為可選用?
,所以在合同上可以省略它,但是在validate
function 中,您然后使用exlude
(在崩潰的行中)而不首先檢查它是否為undefined
,因此您最終調用undefined.includes(p)
!
老實說,我不確定為什么 TypeScript 編譯器此時沒有抱怨。 (也許評論者知道為什么......)
無論如何,解決方案是在validate.ts
中的 function 定義中設置[]
的默認值:
export function validate(target: any, exlude: string[] = []): ObjectErrors {
(當然,在調用 function( validate(IDI, [])
)時,將第二個參數作為空數組傳遞也可以,但是validate
中的錯誤仍然存在。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.