1

运行测试时出现此错误:

RUNTIME EXCEPTION  Exception occurred while loading your tests

TypeError: Cannot read property 'indexOf' of undefined
  at /Users/user/project/.tmp/mocha-webpack/1503105850474/webpack:/~/leaflet/dist/leaflet-src.js:724:1
  at /Users/user/project/.tmp/mocha-webpack/1503105850474/webpack:/~/leaflet/dist/leaflet-src.js:843:2

我有一个使用 mapbox.js 和 leaflet.js 的反应组件。当我有上述错误时

import L from 'mapbox.js';
import 'leaflet.markercluster';

在文件的顶部。componentDidUpdate但是如果我把它移到

const L = require('mapbox.js');
require('leaflet.markercluster');

然后测试正常运行。我认为这可能表明 DOM 不可用存在问题,但即使在我的测试设置中使用 jsdom 也不能解决问题。

require('babel-register')();
require('babel-polyfill');
require('isomorphic-fetch');

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

function copyProps(src, target) {
  const props = Object.getOwnPropertyNames(src)
  .filter(prop => typeof target[prop] === 'undefined')
  .map(prop => Object.getOwnPropertyDescriptor(src, prop));
  Object.defineProperties(target, props);
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

我的测试非常简单:

import React from 'react';
import { Component } from 'components/Component';
import { mount } from 'enzyme';
import { expect } from 'chai';

describe('(Component) HeaderBlockMap', () => {
  let wrapper;
  let search;

  beforeEach(() => {
    wrapper = mount(<Component />);
  });

  it('renders a container', () => {
    const container = wrapper.find('.container');
    expect(container).to.exist;
  });
});
4

0 回答 0