首页 文章

通过CI和本地测试时,Jest快照不同

提问于
浏览
5

我已经实现了jest快照测试,效果很好 . 我唯一无法解决的是我的组件在我的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 具有不同的值 . 什么可能导致我的本地和我的远程测试之间的这种差异?

1 回答

  • 8

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


    这是一个known issue,将在Jest v16(source)中修复 . 在PR #1752中修复 .

    Node.js如何处理函数名称存在问题 . 如果在本地计算机和CI上使用 the exact same version of Node.js 应该没问题 .

    有关您的信息,JEST中的解决方案是从快照中删除名称 . 它看起来像这样:

    optionComponent={[Function]}
    

    问题中的技巧/黑客pointed是将函数包装在匿名函数中:

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

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

相关问题