使用笑话和酶对传单进行单元测试时,未定义layerGroup()



我正在尝试测试我的MyCustomMap是否正在调用我的MapController并创建一个新的传单映射组件。

然而,MapControllerMyCustomMap组件上将_mapGroup设置为undefined,并且它应该是L.layerGroup()(而不是undefined(。

我已经尝试过用不同的方式模拟MapControllerleaflet,但_mapGroup仍然是undefined。怎么了?我该如何解决这个问题?

MyCustomMap测试文件(custom-map.test.js(:

import MyCustomMap from './custom-map';
import initialMapOptions from './map-options';
import MapController from './map-controller';
const mapCreateGroupMock = jest.fn(),
mapAddGroupToMap = jest.fn();
let myMap = null,
mapController = null;
beforeAll(() => {
const mapOptions = initialMapOptions();
mapController = {
createGroup: mapCreateGroupMock,
addGroupToMap: mapAddGroupToMap
};
myMap = new MyCustomMap(mapController, mapOptions);
});
describe('My custom map', () => {
it(`should call MapController and create a new leaflet map component`, () => {
expect(mapCreateGroupMock).toBeCalledTimes(1);
expect(mapAddGroupToMap).toBeCalledTimes(1);    
expect(myMap._mapGroup).not.toBeNull();     // -> here is failing because myMap._mapGroup is undefined and shouldn't be
});
});

My MapController(map controller.js(:

import L from 'leaflet';
class MapController {
constructor(container, configuration) {
this._map = new L.Map(container, { zoomControl: false, minZoom: this._minZoom });
this._container = document.getElementById(container);
//more code here ...
}
createGroup() {
return L.layerGroup();
}

addGroupToMap(group) {
this._map.addLayer(group);
}
//more code here ...
}
export default MapController;

MyCustomMap组件(custom-map.js(:

class MyCustomMap {
constructor(mapController, configuration) {
this._mapController = mapController;
this._configuration = configuration;
this._mapGroup = this._mapController.createGroup();
this._mapController.addGroupToMap(this._mapGroup);
//more code here ...
}
}

已解决!我的mapCreateGroupMock只是返回一个空函数,我需要模拟一个返回值。所以我:

  • 嘲笑了这个价值观
  • 对我的mock函数执行mockClear()
  • 在CCD_ 15上做了每一步
  • 并将我的CCD_ 16断言更改为CCD_

现在它按预期工作。

MyCustomMap测试文件(custom-map.test.js(的最终更改:

import MyCustomMap from './custom-map';
import initialMapOptions from './map-options';
const mapCreateGroupMock = jest.fn(),
mapAddGroupToMap = jest.fn(),
mapOptions = initialMapOptions();  
let myMap = null,
mapController = null;
describe('My custom map', () => {
beforeEach(() => {
mapCreateGroupMock.mockClear();
mapAddGroupToMap.mockClear();
const addLayerMock = jest.fn(),
mapGroup = {
addLayer: addLayerMock
};
mapCreateGroupMock.mockReturnValueOnce(mapGroup);
mapController = {
createGroup: mapCreateGroupMock,
addGroupToMap: mapAddGroupToMap
};
myMap = new MyCustomMap(mapController, mapOptions);
});
it(`should call MapController and create a new leaflet map component`, () => {
expect(mapCreateGroupMock).toBeCalledTimes(1);
expect(mapAddGroupToMap).toBeCalledTimes(1);
expect(myMap._mapGroup).toBeTruthy();
});
});

相关内容

  • 没有找到相关文章