我正在尝试测试我的MyCustomMap
是否正在呼叫我的MapController
并创建一个新的传单地图组件。
不过,MapController
在_mapGroup
组件上将undefined
设置为MyCustomMap
,它应该是L.layerGroup()
(而不是undefined
)。
我已经尝试用不同的方式模拟MapController
和leaflet
,但是_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
});
});
我的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 ...
}
}
答案 0 :(得分:0)
解决了!我的mapCreateGroupMock
只是返回一个空函数,我需要模拟一个返回值。所以我:
mockClear()
; beforeEach()
上执行吗?myMap._mapGroup
断言更改为.toBeTruthy()
,以检查是否未定义且不为空。现在它可以正常工作了。
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();
});
});