为什么我的“react-scripts”测试无法识别 Jest 函数“toMatchObject”?

Why does my `react-scripts` test not recognize the Jest function `toMatchObject`?

我正在测试一个 React 应用程序,它基本上遵循了官方认可的标准 create-react-app 设置。

我写的测试如下:

import React from 'react';
import {shallow} from 'enzyme';

import MyComponent from './MyComponent';

describe('MyComponent', () => {
    it('should have the expected properties', () => {
        const wrapper = shallow(<MyComponent/>);
        expect(wrapper.props()).toMatchObject({a: 1});
    });
});

我的 package.json 包含以下内容:

{
  ...
  "devDependencies": {
    "enzyme": "^2.6.0",
    "react-scripts": "0.8.3",
    ...
  },
  "dependencies": {
    "react": "^15.4.1",
    ...
  },
  "scripts": {
    "test": "react-scripts test --env=jsdom",
    ...
  },
  "jest": {
    "automock": false
  }
}

当我 运行 测试时,我收到以下错误消息:TypeError: expect(...).toMatchObject is not a function

然而,react-scripts documentation states that Jest is one of the built-in tools used, e.g. I don't have to npm install it. And the Jest documentation 清楚地表明 toMatchObject 一个函数。

为什么我会收到此错误消息?

tl;dr: 运行 npm install jest 获取最新的 (v18+) 笑话。

2016 年 12 月初的原始答案:

我发现这是 Jest 本身的问题。据记载 here. If I read it correctly, it's not so much a bug as it is a feature-in-the-works that made its way into the documentation before it was actually ready for public release. Apparently, it should be coming out any day now. In the mean time, someone (the Jest team? someone else?) has provided a helper which can be found here 填写这个匹配器直到它正式可用。我还没有真正尝试过这个助手,我怀疑它可能很快就会消失,但我想如果感兴趣的读者真的想要这个功能,我会让他们知道。

2017年1月上旬更新:

根据 this websitetoMatchObject 匹配器大约在 2017 年 1 月 3 日包含在 Jest 中。那是 Jest v18(18.0.0?...目前是 18.1.0) .这仍然没有包含在基本的 React 下载中,因为当我删除我的 node_modules 文件夹并重新 npm install-ed 一切时,这个匹配器仍然对我不起作用。但是,如果我专门用 npm install jest 更新了 jest,那么 node_modules/jest/package.json 表示 jest 现在已经更新(对我来说,2017 年 1 月 15 日,更新到版本 18.1.0)并且 toMatchObject 现在似乎工作。

...实际上,上段的解决方案似乎变化无常,因为它确实在我最初使用它时有效,但不久之后又停止工作(之后再次重新删除 node_modules,重新 npm install 一切,重新做 npm install jest,甚至尝试@Scimonster 从评论中提出的建议,即删除 node_modules/react-scripts/node_modules/jest)。我确实找到了另一个可行的 hack:手动将实际的 toMatchObject 代码从 here 添加到 node_modules/react-scripts/node_modules/jest-matchers/build/matchers.js(在恢复一些 ES6/typescript/babel?-ish 语法之后)。我想这一切都会在不久的将来对 React 的更新中得到解决,但现在这对我有用(至少目前是这样!)。