1

我有以下方法可以根据给定属性从数组中删除重复项:

   removeDuplicates(myArr, prop) {
        return myArr.filter((object, pos, arr) => {
            return arr.map(obj => obj[prop]).indexOf(object[prop]) === pos;
        });
    }

现在我需要对这个方法进行单元测试,但我不知道怎么做。

describe('remove duplicates', () => {
  it('should remove duplicated objects from an array based on a property', () => {
   //..
  }
});

我怎样才能正确测试这样的方法?

4

2 回答 2

1

你导入你的removeDuplicates函数。

您可以遵循 AAA 模式(Arrange Act Assert)。

describe('removeDuplicates', () => {
  const fixtureComponent = TestBed.createComponent(YourComponent);
  it('should remove objects with same given property', () => {
   // Arrange
   const persons = [
     { id: 1, name: 'John' },
     { id: 2, name: 'Paul' },
     { id: 3, name: 'Ron' },
     { id: 4, name: 'John' },
     { id: 5, name: 'Louis' },
   ];

    // Act
    const distinctPersons = fixtureComponent.removeDuplicates(persons, 'name');

   // Assert
   expect(distinctPersons).toEqual([
     { id: 1, name: 'John' },
     { id: 2, name: 'Paul' },
     { id: 3, name: 'Ron' },
     { id: 5, name: 'Louis' },
   ]);
 }
});
于 2019-11-15T08:48:03.137 回答
1

如果这是一项服务,试试这个

describe('removeDuplicates', () => {

  beforeEach(() => TestBed.configureTestingModule({
   providers: [
    YourServiceService 
   ]
  }));

  it('should remove objects with same given property', () => {

   const service: YourServiceService = TestBed.get(YourServiceService );

   const persons = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Paul' },
    { id: 3, name: 'Ron' },
    { id: 4, name: 'John' },
    { id: 5, name: 'Louis' },
   ];

   let results = service.removeDuplicates(persons, 'name' );
   expect(results ).toBe([
    { id: 1, name: 'John' },
    { id: 2, name: 'Paul' },
    { id: 3, name: 'Ron' },
    { id: 5, name: 'Louis' },
   ]);
  })
})
于 2019-11-15T09:00:00.613 回答