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

时间:2017-07-21 09:40:20

标签: javascript unit-testing jasmine karma-jasmine

我正在尝试为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

        });
    });
});

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

1 个答案:

答案 0 :(得分: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)
    })
  })
})