我正在测试我的自定义管道:NoCommaPipe。但是,当我用输入10,000,000创建测试时,它返回NaN。我该如何使用以下输入创建测试:10,000,000
no-comma.pipe.ts:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: 'noComma'
})
export class NoCommaPipe implements PipeTransform {
transform(val: number): string {
let transformedVal: string;
if(val === undefined || val === null) {
transformedVal = ""
} else {
transformedVal = val.toString().replace(/,/g, "");
}
return transformedVal;
}
}
no-comma.pipe.spec.ts:
import { NoCommaPipe } from './no-comma.pipe';
fdescribe('NoCommaPipe', () => {
let noCommaPipe: NoCommaPipe;
beforeEach(() => {
noCommaPipe = new NoCommaPipe();
})
it('should create', () => {
expect(noCommaPipe).toBeTruthy();
})
it('should return empty string on input is undefined', () => {
expect(noCommaPipe.transform(undefined)).toEqual('');
})
it('should return empty string on input is null', () => {
expect(noCommaPipe.transform(null)).toEqual('');
})
it('should return 10000000 on input equal to 10,000,000', () => {
expect(noCommaPipe.transform(Number('10,000,000'))).toEqual('10000000');
})
})
答案 0 :(得分:2)
它返回NaN,因为这是您要提供给方法的参数:
console.log(Number('10,000,000'));
您可以在此处看到,如果您不使用Number()
,它将按预期工作。
function transform(val) {
let transformedVal;
if (val === undefined || val === null) {
transformedVal = ""
} else {
transformedVal = val.toString().replace(/,/g, "");
}
return transformedVal;
}
console.log(transform(Number('10,000,000')));
console.log(transform('10,000,000'));
回应评论...
console.log(typeof('10,000,000'));
console.log(typeof(10000000));
console.log(10,000,000);
答案 1 :(得分:1)
您正在通过考试
Number('10,000,000')
它将始终返回NaN,因为10,000,000不被识别为数字,而不是字符串。 没有理由将您的transform属性作为数字传递给指令,因为您收到的值将始终是字符串...
只需将val: number
更改为val: string
或any
,然后将演员表移至数字