使用Jasmine单元测试过滤器组件

时间:2019-04-02 11:57:43

标签: javascript angularjs karma-jasmine

我创建了一个组件,用于过滤掉传递给它的字符串。我正在尝试为此编写单元测试,它引发了与构造函数有关的错误。请帮助我。

import angular from 'angular';
import filter from "./format-string.filter"

angular
.module( "filters.truncateString", [] )
.filter( "truncateString", () => filter );

class TruncateString {
 filter(val){
    const accValue = val.split('YYYY');
    const firstValue= accValue[1].replace(/^(|-?\d+)$/, '');
    return `${accValue[0]} ${firstValue} AAA`;
 }
}

export default TruncateString .filter;`

我写的测试是

import angular from 'angular';
import 'angular-mocks';
import TruncateString from './format-string.filter';
describe('TruncateString filter', () => {
let controller, filter;

beforeEach(angular.mock.module('filters.TruncateString'));
controller = new TruncateString();

beforeEach(inject(function(_$filter_){
    filter = _$filter_;
}));

it('Checking whether the function is returning formatted string', () => {
    const result = controller.filter('123YYY3213123');
    expect(result).toHaveBeenCalledWith('123 YYY ... 23');
});
});

1 个答案:

答案 0 :(得分:1)

这是测试过滤器的方法

describe('Test My Filter', () => {
  let $filter;

  beforeEach(() => {
    module('filters.TruncateString');

    inject((_$filter_) => {
      $filter = _$filter_;
    });
  });

  it('should test filter behavior', () => {
    let result = $filter('truncateString')('testval');
    expect(result).toEqual('expectedval');
  });
});