通过 CI 测试与本地测试时的开玩笑快照不同

Jest snapshot different when testing through CI vs locally

我已经实施了开玩笑的快照测试,效果很好。我唯一无法解决的是我的组件在 CI 上呈现不同的快照。我的测试是:

/* eslint-env jest */
/* eslint import/no-extraneous-dependencies: "off" */

import React from 'react';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import Combobox from '../Combobox';

describe('<Combobox />', () => {
  it('renders correctly', () => {
    const wrapper = shallow(
      <Combobox
        items={[]}
        placeholder=""
        valueKey=""
        labelKey=""
      />
    );

    expect(shallowToJson(wrapper)).toMatchSnapshot();
  });
});

组件是:

import React, { PropTypes } from 'react';
import Select from 'react-select';

export default class Combobox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentValue: null,
    };
    this.updateValue = this.updateValue.bind(this);
  }

  updateValue(newValue) {
    this.setState({
      currentValue: newValue,
    });
  }

  render() {
    return (
      <Select
        placeholder={this.props.placeholder}
        valueKey={this.props.valueKey}
        labelKey={this.props.labelKey}
        options={this.props.items}
        value={this.state.currentValue}
        onChange={this.updateValue}
      />
    );
  }
}

Combobox.propTypes = {
  items: PropTypes.array.isRequired,
  placeholder: React.PropTypes.string.isRequired,
  valueKey: React.PropTypes.string.isRequired,
  labelKey: React.PropTypes.string.isRequired,
};

我正在使用 enzymeenzyme-to-json 生成快照。该组件本身是 react-select 的包装器。在本地测试时一切正常,但在我的 CI 上出现错误:

FAIL  src/components/__tests__/Combobox.test.jsx
  ● <Combobox /> › renders correctly

    Received value does not match the stored snapshot 1.

    - Snapshot
    + Received

    <Select
        // ...
    -   optionComponent={[Function anonymous]}
    +   optionComponent={[Function Constructor]}
        // ...
    -   valueComponent={[Function anonymous]}
    +   valueComponent={[Function Constructor]}
        valueKey="" />

      at Object.<anonymous> (src/components/__tests__/Combobox.test.jsx:20:82)
      at process._tickCallback (internal/process/next_tick.js:103:7)

因此,与我的本地快照相比,optionComponentvalueComponent 具有不同的值。是什么导致了我的本地测试和远程测试之间的这种差异?

更新 (2016 年 10 月 3 日):Jest 16.0 已发布 with the fix


这是一个known issue and will be fixed in Jest v16 (source). Fixed in PR #1752

Node.js 处理函数名称的方式存在问题。如果您在本地计算机上使用 完全相同的 Node.js 版本和 CI.

应该没问题

供您参考,JEST 中的解决方案是从快照中删除名称。它看起来像这样:

optionComponent={[Function]}

问题中的一个trick/hackpointed是将函数包装在一个匿名函数中:

-      onSelect={onSelectHandler}
+      onSelect={(...args) => onSelectHandler(...args)}

不幸的是,这必须在 react-select 库中发生。