如何使用Jasmine对init()函数进行单元测试?

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

我正在尝试为init函数编写单元测试,并且我在测试中调用collectionReport.init()时出现错误....

TypeError:undefined不是对象

这是我试图测试的代码......

class CollectionsReport {
    constructor({ editCollectionsId, hasCollections}) {

    this.editCollectionsId = editCollectionsId;
    this.hasCollections = hasCollections
}

init({ id, name }) {
    this.id = id;
    this.name = name;

    // need to test this
    if (this.hasCollections) {
        this.collection = this.collections.find(c => c.staticId === 'CAR-COLLECTION');
    }
}

到目前为止,这是我的测试

describe('CollectionsReport', () => {
    const collectionArgs = {
        editCollectionsId: jasmine.createSpy(),
        hasCollections: false,
    };

    const collections = [
            {
                id: 1,
                name: 'foo',
                staticId: 'CAR-COLLECTIONS',
            },
            {
                id: 2,
                name: 'bar',
                staticId: 'TRUCK-COLLECTIONS',
            },
        ];

    let collectionReport;

    beforeEach(() => {
        collectionReport = new CollectionsReport(collectionArgs);
    });

    describe('.init()', () => {
        it('should test hasCollections', () => {
            collectionReport.init();

            //test this.hasCollections here

        });
    });
});

我确定它一团糟,所以请评论如何修复和改进它。

javascript unit-testing jasmine karma-jasmine
1个回答
0
投票

不确定CollectionsReport课程的目的是什么,但也许这将引导您走向正确的方向:

class CollectionsReport {
  constructor({ editCollectionsId, hasCollections}) {
    this.editCollectionsId = editCollectionsId
    this.hasCollections = hasCollections
  }

  init({ collections, staticId }) {
    this.hasCollections = !!collections.find(c => c.staticId === staticId)
  }
}

describe('CollectionsReport', () => {
  const collectionArgs = {
    editCollectionsId: jasmine.createSpy(), // Not really using it
    hasCollections: false
  }

  const collections = [
    {
      id: 1,
      name: 'foo',
      staticId: 'CAR-COLLECTIONS'
    }, {
      id: 2,
      name: 'bar',
      staticId: 'TRUCK-COLLECTIONS'
    }
  ]

  describe('.init()', () => {
    let collectionReport
    beforeEach(() => {
      collectionReport = new CollectionsReport(collectionArgs)
    })

    it('should test hasCollections', () => {
      collectionReport.init({ collections, staticId: 'CAR-COLLECTIONS' })

      expect(collectionReport.hasCollections).toBe(true)
    })

    it('should test hasCollections', () => {
      collectionReport.init({ collections, staticId: 'SOMETHING-ELSE' })

      expect(collectionReport.hasCollections).toBe(false)
    })
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.