我正在尝试为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
});
});
});
我确定它一团糟,所以请评论如何修复和改进它。
不确定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)
})
})
})