gpt4 book ai didi

javascript - 在 Angular 中测试自定义管道

转载 作者:行者123 更新时间:2023-11-30 11:31:56 26 4
gpt4 key购买 nike

我正在尝试为我的自定义管道编写一些基本测试,但作为 Jasmine 和 Angular 管道的新手,我遇到了一些困难。这是我的 pipe :

十进制格式管道.js

import { Pipe , PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Pipe({
name: 'myDecimalFormatingPipe'
})

export class MyDecimalFormatPipe implements PipeTransform {

constructor(public decimalPipe: DecimalPipe) {};

transform(value: any) {
if (value || value === 0) {
value = this.decimalPipe.transform(value, '1.2-2');
}
return value;
}
}

显然,这个“自定义”管道现在只是简单地实现了十进制管道 transform(),但将来会发生变化。

这是我的规范:

import { MyDecimalFormatPipe } from './my-decimal-format.pipe';
import { DecimalPipe } from '@angular/common';

describe('MyDecimalFormatPipe', () => {

let pipe: MyDecimalFormatPipe;
let decimalPipe: DecimalPipe;
let inputValue: any = '2.1111';

beforeEach( () => {
decimalPipe = new DecimalPipe(inputValue);
myPipe = new MyDecimalFormatPipe(decimalPipe);
});

it('pipe is defined', () => {
expect(pipe instanceof MyDecimalFormatPipe).toBeTruthy();
});

describe('transform ', () => {
it('should return correct value type ', () => {

spyOn(decimalPipe, 'transform').and.callThrough();

decimalPipe.transform(inputValue, '1.2-2');

expect(decimalPipe.transform).toEqual('2.11');
});
});
});

我的第一个规范通过了,但是对于 transform() 测试它失败了,我得到了

error: 
RangeError: Invalid language tag: 2.1111
at new NumberFormat (native)
at Function.NumberFormatter.format (

我不记得上次看到这个错误是什么时候了。 “无效的语言标签”指的是什么?是什么让这个规范崩溃了?

最佳答案

正在完成 y_vyshnevska的回答,有几点需要注意:

  • 您需要使用 decimalPipe = new DecimalPipe('arab');告诉DecimalPipe使用阿拉伯数字格式的构造函数(在您的情况下)。
  • 根据官方文档,我相信您不需要为此测试使用 spy (https://angular.io/guide/testing#pipes),但只需从管道获取返回结果就足够了。

编辑部分:

beforeEach(() => {
decimalPipe = new DecimalPipe('arab');
pipe = new MyDecimalFormatPipe(decimalPipe);
});

...

it('should return correct value type ', () => {
// spyOn(pipe, 'transform').and.callThrough();
const result = pipe.transform(inputValue);
expect(result).toEqual('2.11');
});
...

N.B:我可以见证的一件有趣的事情是,使用 Headless chrome,测试将通过,因为结果是正确的 (2.11);但在我的 chrome 浏览器中,测试会失败,说结果不正确 (2,11)。我猜这是由于浏览器设置造成的,但我也没想到 :-)

关于javascript - 在 Angular 中测试自定义管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com