【问题标题】:Mock Bing Maps API with Jest in React.js在 React.js 中使用 Jest 模拟 Bing 地图 API
【发布时间】:2019-06-26 12:05:52
【问题描述】:

在我的 Jest 测试中,我需要像这样生成一个 Bing 地图图钉:

it('...', () => {
  var e = new window.Microsoft.Maps.Pushpin({ "latitude": 56.000, "longitude": 46.000 }, {});
  /* do stuff */
  expect(e.getColor()).toEqual('#ffd633');
})

但是当我运行测试时,我得到了错误:

TypeError: Cannot read property 'Maps' of undefined

有人知道如何在 React 中模拟 Bing Maps API Microsoft 与 Jest 的接口吗?

【问题讨论】:

    标签: reactjs testing mocking jestjs bing-maps


    【解决方案1】:

    一种选择是引入 Bing Maps API 类模拟并通过beforeAll Jest setup function 注册它,如下所示:

    const setupBingMapsMock = () => {
      const Microsoft = {
        Maps: {
          Pushpin : class {
            location = null;
            options = null;
            constructor(location,options) {
              this.location = location;
              this.options = options;
            }
    
            getColor(){
              return this.options.color;
            }
          }
        }
      };
    
      global.window.Microsoft = Microsoft;
    };
    
    beforeAll(() => {
      setupBingMapsMock();
    });
    
    it("creates a marker", () => {
      const e = new window.Microsoft.Maps.Pushpin(
        { latitude: 56.0, longitude: 46.0 },
        {'color': '#ffd633'}
      );
      expect(e.getColor()).toEqual("#ffd633");
    });
    

    结果

    【讨论】:

    • 这似乎不适用于当前版本的打字稿。
    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2020-12-17
    • 1970-01-01
    • 2020-07-25
    相关资源
    最近更新 更多