programing

스냅샷을 생성할 때 Jest/Enzym ShowlowWrapper가 비어 있습니다.

codeshow 2023. 3. 23. 23:00
반응형

스냅샷을 생성할 때 Jest/Enzym ShowlowWrapper가 비어 있습니다.

그래서 나는 아이템 컴포넌트에 대한 테스트를 쓰고 있는데, 나는 그 컴포넌트를 렌더링하려고 했다.ItemCard컴포넌트를 사용하여 스냅샷을 생성하지만 빈 컴포넌트가 반환됩니다.ShallowWrapper {}

자세한 내용은 다음 코드를 참조하십시오.

Item.test.js

import { shallow } from 'enzyme';
import { ItemCard } from '../Item';

const fakeItem = {
  id: 'aksnfj23',
  title: 'Fake Coat',
  price: '40000',
  description: 'This is suuuper fake...',
  image: 'fakecoat.jpg',
  largeImage: 'largefakecoat.jpg',
};

describe('<ItemCard/>', () => {
  it('renders and matches the snapshot', () => {
    const wrapper = shallow(<ItemCard me item={fakeItem} showButtons />);

    // console.log(wrapper.debug());
    expect(wrapper).toMatchSnapshot();
  });
});

스냅 생성:

// Jest Snapshot v1

exports[`<ItemCard/> renders and matches the snapshot 1`] = `ShallowWrapper {}`;

ShallowWrapper는 비어있는 것이 아니라 내용물이 들어있어야 한다는 것을 알고 있습니다.

v24의 농담으로 https://github.com/adriantoine/enzyme-to-json와 같은 스냅샷 시리얼라이저를 사용해야 합니다.

출처 : https://github.com/facebook/jest/issues/7802

버전을 되돌릴 필요는 없습니다.공식 델 텔레폰 어드바이저에 따름

Jest 설정에 다음 항목을 추가해야 합니다.

"snapshotSerializers": ["enzyme-to-json/serializer"]

단서: 패키지에 추가하는 것만으로 간단합니다.json, 예를 들어:

{
  "name": "my-project",
  "jest": {
    "snapshotSerializers": ["enzyme-to-json/serializer"]
  }
}

정답이 아니었다면 죄송합니다.여기서 아무도 말하지 않는 걸 봤는데 몇 분 전에 나처럼 길을 잃은 사람들에게 도움이 될 거야.

jeast@24.0.0으로 업데이트한 후 같은 문제에 직면했습니다.당분간 이전 버전 jeast@23.6.0으로 되돌렸습니다.변경된 내용을 찾으면 여기에 게시하십시오.

를 사용해야 합니다.jest-enzyme예를 들어 다음과 같습니다.

https://github.com/airbnb/enzyme/issues/1533#issuecomment-479591007

마운트 및 디버깅 기능은 다음과 같이 사용할 수 있습니다.

it('Should render Component', () => {
    const wrapper = mount(<Component {...props} />);
    expect(wrapper.debug()).toMatchSnapshot();
  });

래퍼 뒤에 debug() 메서드를 사용합니다.

  it('renders and matches the snapshot', () => {
const wrapper = shallow(<ItemCard me item={fakeItem} showButtons />);

// console.log(wrapper.debug());
expect(wrapper.debug()).toMatchSnapshot(); });

같은 문제에 직면하여 시리얼라이저 https://github.com/adriantoine/enzyme-to-json을 사용하여 해결했습니다.

npm install --save-dev 효소-to-json

효소 대 json을 설치한 후에는 다음과 같은 것을 사용할 수 있습니다.

import React, {Component} from 'react';
import {shallow} from 'enzyme';
import toJson from 'enzyme-to-json';

it('renders correctly', () => {
  const wrapper = shallow(
    <MyComponent className="my-component">
      <strong>Hello World!</strong>
    </MyComponent>,
  );

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

같은 문제를 해결할 수 있습니다.shallow().debug()그러나 위의 방법을 사용하는 것을 선호합니다.

조금 늦었지만, https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/getElement.html을 사용하여 이 문제를 해결할 수 있었습니다.

describe("Button", () => {
  it("should render basic button correctly", () => {
    const tree = shallow(<Button></Button>);
    expect(tree.getElement()).toMatchSnapshot();
  });
});

에 관한 이 작업Jest 26.5.3그리고.enzyme 3.10.5

제 사례를 공유합니다.

내가 받기 전에:

내보내기<ItemCard/> renders and matches the snapshot 1] =ShallowWrapper {};

모든 것이 예상대로 작동하도록 두 곳을 변경했습니다.

  1. 섬유 첨가 효소

  2. 패키지의 JEST 설정에 이 행을 추가했습니다.json:

"snapshotSerializers": ["enzyme-to-json/serializer"]

제 소포입니다.json:

"dependencies": {
    "next": "11.0.0",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@babel/preset-env": "7.14.5",
    "@babel/preset-react": "7.14.5",
    "@types/jest": "^26.0.23",
    "@wojtekmaj/enzyme-adapter-react-17": "^0.6.2",
    "babel": "^6.23.0",
    "babel-jest": "^27.0.2",
    "enzyme": "^3.11.0",
    "enzyme-to-json": "^3.6.2",
    "eslint": "7.29.0",
    "eslint-config-next": "11.0.0",
    "jest": "^27.0.4"
  },
  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>/setupTests.js"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  }

언급URL : https://stackoverflow.com/questions/54419342/jest-enzyme-shallowwrapper-is-empty-when-creating-snapshot

반응형