2

我不知道为什么我shallowWrapper在运行快照测试时得到空对象,我正在使用JestEnzyme

我在App.test.js.snap文件中得到什么:

// Jest Snapshot v1, "goo.gl/fbAQLP"
exports[`renders App component 1`] = `ShallowWrapper {}`;

我的package.json文件:

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.30",
    "@fortawesome/free-solid-svg-icons": "^5.14.0",
    "@fortawesome/react-fontawesome": "^0.1.11",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "bootstrap": "^4.5.2",
    "install": "^0.13.0",
    "npm": "^6.14.8",
    "react": "^16.13.1",
    "react-bootstrap": "^1.3.0",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.0-next.98"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.4",
    "jest": "^26.4.2"
  }
}

App.test.js文件

import { shallow } from 'enzyme';
import React from 'react';
import App from './App';


it('renders App component', () => {
  expect(shallow(<App />)).toMatchSnapshot();
})

setupTests.js文件:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ 
    adapter: new Adapter()
 });

为什么我得到那个空shallowWrapper对象,经过一番搜索,我怀疑是 jest 的版本,但即使降级也没有解决它。

4

2 回答 2

4

我遇到了类似的问题并开玩笑帮助我解决了这个问题。我建议您可以清除 jest 缓存,然后使用更新快照jest --clearCache && jest -u,然后运行测试。

同样对于您的快照,我建议您使用enzyme-to-json序列化程序(https://www.npmjs.com/package/enzyme-to-json)并将您的测试修改为:

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

it('renders App component', () => {
  const app = shallow(<App />);
  expect(shallowToJson(app)).toMatchSnapshot();
})
于 2020-09-22T08:12:55.237 回答
1

shallow() 确实返回了输出。Shallow 用作渲染输出的包装器实例。你可以使用 shallow() 方法和 debug() 来查看打印出来的内容。如果你想看到渲染的输出,你可以在 expect() 方法中使用 shallow().html() 再次测试。

于 2020-09-22T07:18:19.103 回答