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

问题描述 投票:0回答:1

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

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');
});
});
javascript angularjs karma-jasmine
1个回答
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');
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.