programing

「 」를 「 」를 「 」를 제스트 시험을 지원해주실 수 있나요?

showcode 2023. 3. 31. 23:02
반응형

「 」를 제스트 시험을 지원해주실 수 있나요?

제스트 유닛 테스트에서는 ColorPicker로 컴포넌트를 렌더링하고 있습니다.ColorPicker하지만 2D 콘텍스트를 반환합니다.'undefined'시킵니다."Cannot set property 'fillStyle' of undefined"

if (typeof document == 'undefined') return null; // Dont Render On Server
var canvas = document.createElement('canvas'); 
canvas.width = canvas.height = size * 2;
var ctx = canvas.getContext('2d'); // returns 'undefined'
ctx.fillStyle = c1; // "Cannot set property 'fillStyle' of undefined"

2D 콘텍스트를 얻을 수 없는 이유를 이해하는데 어려움을 겪고 있습니다.테스트 구성에 문제가 있을 수 있습니다.

"jest": {
  "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
  "unmockedModulePathPatterns": [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils",
    "<rootDir>/node_modules/react-tools"
  ],
  "moduleFileExtensions": [
    "jsx",
    "js",
    "json",
    "es6"
  ],
  "testFileExtensions": [
    "jsx"
  ],
  "collectCoverage": true
}

create-react-app을 사용한 예를 찾고 있는 고객용

설치하다

yarn add --dev jest-canvas-mock

" " " 를 .${rootDir}/src/setupTests.js 함께

import 'jest-canvas-mock';

실제 브라우저에서 테스트가 실행되지 않기 때문입니다.는 Jeest를 합니다.jsdom노드 내에서 테스트를 실행하기 위해 필요한 DOM 부분을 조롱하기 위해 브라우저가 일반적으로 수행하는 스타일 계산 및 렌더링을 피할 수 있습니다.이것은 시험을 빨리 볼 수 있게 해주기 때문에 멋집니다.

한편 컴포넌트에 브라우저 API가 필요한 경우 브라우저보다 더 어렵습니다.다행히 캔버스에 대한 지원이 있습니다.설정하기만 하면 됩니다.

jsdom에는 캔버스 패키지를 사용하여 다음을 확장하기 위한 지원이 포함되어 있습니다.<canvas>츠키노이 작업을 수행하려면 캔버스를 jsdom의 피어로 프로젝트에 종속적으로 포함해야 합니다.패키지를 수 경우 캔버스 패키지를 할 수 경우 jsdom 패키지가 됩니다.<canvas> 음음음음음 like like like like like like like like like like like like like like like처럼 행동합니다.<div>s.

또는 Jest를 Karma와 같은 브라우저 기반의 테스트 주자로 대체할 수도 있습니다.어쨌든 농담은 꽤 지루하다.

라이브러리 노드 캔버스가 설치되어 있는 경우 Jest / jsdom은 캔버스 요소를 처리할 수 있습니다.

해서 제거해 주세요.jest-canvas-mock되어 있는 ) 및 (「」)canvas:

npm uninstall jest-canvas-mock
npm i --save-dev canvas

제 활용 사례는 이렇게 간단한 원숭이 패치를 적용했습니다.

beforeEach(() => {
    const createElement = document.createElement.bind(document);
    document.createElement = (tagName) => {
        if (tagName === 'canvas') {
            return {
                getContext: () => ({}),
                measureText: () => ({})
            };
        }
        return createElement(tagName);
    };
});

캔버스 프리빌트 또는 sinon을 설치할 필요가 없습니다.

나도 똑같은 문제가 있었어.테스트를 실행하기 위해 gitlab ci에 배치하려고 합니다.npm 캔버스는 카이로 설치가 필요하기 때문에 실행 가능한 옵션이 아니었습니다.

제가 정말 하고 싶었던 것은 Jest를 통한 구현을 조롱하는 것이었습니다. 그래야 실제 컨텍스트를 만들려 하지 않습니다.해결 방법은 다음과 같습니다.

패키지에 추가되었습니다.json

"jest": {
  "setupFiles": ["./tests/setup.js"],
}

tests/syslog.displaces

import sinon from 'sinon';

const createElement = global.document.createElement;
const FAKECanvasElement = {
  getContext: jest.fn(() => {
    return {
      fillStyle: null,
      fillRect: jest.fn(),
      drawImage: jest.fn(),
      getImageData: jest.fn(),
    };
  }),
};

/**
 * Using Sinon to stub the createElement function call with the original method
 * unless we match the 'canvas' argument.  If that's the case, return the Fake 
 * Canvas object.
 */
sinon.stub(global.document, 'createElement')
  .callsFake(createElement)
  .withArgs('canvas')
  .returns(FAKECanvasElement);

재담-재담-재담-재담-재담-재담은 효과가

  1. 「」와 함께 인스톨 .npm i --save-dev jest-canvas-mock

  2. joke.config.js에서 추가합니다."setupFiles": ["jest-canvas-mock"]여하하다
    ( 경우 setupFiles " " " " " " " " " jest - canvas - mock " " " " " " " " " " " " " " " " jest - canvas - mock " " " " " " " " ")."setupFiles": ["something-xyz.js", "jest-canvas-mock"]를 참조해 주세요.

모두 완료.

캔버스 출력을 농담으로 테스트하려면 다음을 수행해야 합니다.

적어도 jsdom 13을 사용하고 있는지 확인합니다.jsom 패키지를 농담으로 포함하면 됩니다.14의 경우 다음과 같습니다.

jest-environment-jsdom-fourteen

그리고 이것을 사용하기 위한 농담 설정

jest --env=jest-environment-jsdom-fourteen

또는package.json

"jest": {
   ...
   "testEnvironment": "jest-environment-jsdom-fourteen",

를 포함하다canvasnpm 패키지( 2.x 에서는 빌드 버전이 포함되어 있기 때문에 캔버스 프리빌트는 권장되지 않습니다).

create-react-app을 사용하는 경우 다음 명령을 사용하여 jest-canvas-mock을 설치합니다.npm i --save-dev jest-canvas-mock테스트 파일 맨 위에import 'jest-canvas-mock'

리액트 테스트 라이브러리 및 jeste-image-snapshot을 사용하여 캔버스에서 이미지 스냅샷 테스트를 만들었습니다.그것은 다소 유행어이지만 잘 작동했다.

node-canvas(jest-canvas-mock 등이 아님)를 사용하여 jest 테스트를 올바르게 셋업할 수 있다면 문자 그대로 Data에 호출할 수 있습니다.캔버스 요소의 URL입니다.


  import {render, waitForElement} from 'react-testing-library'
  import React from 'react'
  import { toMatchImageSnapshot } from 'jest-image-snapshot'

  expect.extend({ toMatchImageSnapshot })

  test('open a canvas', async () => {
    const { getByTestId } = render(
      <YourCanvasContainer />,
    )
    const canvas = await waitForElement(() =>
      getByTestId('your_canvas'),
    )
    const img = canvas.toDataURL()
    const data = img.replace(/^data:image\/\w+;base64,/, '')
    const buf = Buffer.from(data, 'base64')
    expect(buf).toMatchImageSnapshot({
      failureThreshold: 0.001,
      failureThresholdType: 'percent',
    })
  })

travis-CI에서 실행할 때 무작위로 다른 픽셀이 2개 있었기 때문에 이미지/png 데이터 URL을 직접 비교하는 것보다 낮은 임계값을 사용해야 한다는 것을 알게 되었습니다.

또한 jest 환경 jsdom을 jest-environment-dom-dom-dom-dom 또는 jest-environment-dom-dom-dom-dom-dom-dom-dom-dom-dom-dom으로 수동으로 업그레이드하는 것을 검토하고 https://github.com/jsdom/jsdom/issues/1782을 참조하십시오.

저 같은 경우에는 리액트 하고 있어요.

npm uninstall jest-canvas-mock

npm i --save-dev canvas

이 2개의 명령어는 도움이 됩니다.

캔버스 패키지를 인스톨 해 주세요.jest는 캔버스를 div로 변환하기 때문에, 이 패키지를 인스톨 한 후, 테스트 케이스는 캔버스의 동작에 필요한 것과 같이 동작합니다.

npm install canvas

이게 너한테 효과가 있길 바라.

npm install -D canvas-prebuilt@1

이것은 농담을 위한 캔버스를 지원합니다.이것은 Lottie.js로 인해 오류가 발생한 경우에도 작동합니다.

언급URL : https://stackoverflow.com/questions/33269093/how-to-add-canvas-support-to-my-tests-in-jest

반응형