programing

참조 오류:Jest 환경이 해체된 후 파일을 '가져오기'하려고 합니다.

codeshow 2023. 3. 18. 09:11
반응형

참조 오류:Jest 환경이 해체된 후 파일을 '가져오기'하려고 합니다.

a that that that that that that that that that that that that that를 활용한 컴포넌트를 가지고 있습니다.Animated nativeinternative native의 입니다.테스트 케이스를 작성하기 시작했는데onPress의 컴포넌트로, 「」를 가지는 합니다.Animated.timing안에, 그안, 리 insetState.

jest정상적으로 동작하지만 테스트의 실행은 멈추지 않습니다.또, 지금까지 작성한 관련 없는 테스트 케이스가, 지금까지(이러한 경우는) 합격할 수 없는 것 같습니다.

jest --watch , 음음음음음음 음: , , 。

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at Function.bezier (node_modules/react-native/Libraries/Animated/src/Easing.js:113:21)
      at ease (node_modules/react-native/Libraries/Animated/src/Easing.js:34:24)
      at TimingAnimation._easing (node_modules/react-native/Libraries/Animated/src/Easing.js:133:18)
      at TimingAnimation.onUpdate (node_modules/react-native/Libraries/Animated/src/animations/TimingAnimation.js:107:45)

 RUNS  src/__tests__/SlideDownMenu.test.js

/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:114
      return _bezier(x1, y1, x2, y2);
             ^
TypeError: _bezier is not a function
    at Function.bezier (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:224:12)
    at ease (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:94:21)
    at TimingAnimation._easing (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:255:16)
    at TimingAnimation.onUpdate (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/animations/TimingAnimation.js:138:14)
    at ontimeout (timers.js:386:11)
    at tryOnTimeout (timers.js:250:5)
    at Timer.listOnTimeout (timers.js:214:5)

리플리케이션 링크

https://repl.it/repls/PartialGrimyMetadata

환경:

  • OS: Linux 4.14
  • 노드: 6.14.2
  • 실: 1.7.0
  • npm: 3.10
  • 워치맨:찾을 수 없음
  • X코드: 없음
  • Android Studio:찾을 수 없음

좋아, 해결책을 찾았어.

사용하다jest.useFakeTimers()

위 는 "" " " " " " " 바로 에 입력해 .import션션을섹

jeast.use FakeTimers()

위와 함께, 이것을 이해하는 것이 매우 중요하다.

jeast.useFakeTimers()는 setTimeout 및 기타 타이머 함수를 모의 함수로 삭제합니다.

하나의 파일 또는 descript block 내에서 여러 테스트를 실행하는 경우 각 테스트 전에 수동으로 또는 beforeEvel 등의 설정 함수를 사용하여 jeast.useFakeTimers();를 호출할 수 있습니다.

그렇지 않으면 내부 사용 카운터가 리셋되지 않습니다.

"testEnvironment": "jsdom"jest패키지에 열쇠키 인 패키지json or jest.config.jsjson 또는 jeast.config.displays.display

"jest": {
  "testEnvironment": "jsdom",
  "preset": "react-native",
   ...

출처: https://stackoverflow.com/a/64567257/728287

저는 그 답변에 기여하고 싶습니다.

에러 메시지를 표시해 봅시다.

ReferenceError: You are trying to 'import' a file after the Jest environment has been torn down.

해체란 Jest 실행이 이미 완료되었으며 Jest 실행이 완료된 후 코드 일부가 실행하려고 시도하고 있음을 의미합니다.이것은 Javascript의 비동기 특성으로 인해 매우 일반적입니다.

약속 콜백이 실행된 후에 발생할 수 있습니다.예를 들어 다음과 같습니다.

import { someProcess } from 'a-library'

task.job().then(result => {
    someProcess(result)
})

In the example above, the code imports 위의 예에서는 코드가 Import 됩니다.someProcess부에서a-library.

메서드 방이 있으면job에에서task개체는 농담이 아니라, 백 보 래 립 오 걸 니 object execution(, takes다back ( the than longer joke jest call, its실다가젝트브행콜오 object then()초대) 농담이 이미 끝났기 때문에 농담으로 도망갈 것이다.호출)은 joke가 이미 테스트 실행을 마쳤기 때문에 joke 외부에서 실행됩니다., 「 」의 경우는,someProcess됩니다.a-library그래서 농담은 당신이 농담을 분해한 후에 도서관을 읽으려고 한다고 불평할 것이다.

.왜냐하면, 「해답」을 호출하고 있기 입니다.jest.useFakeTimers() 경우 합니다.n통화할 때 초)setTime코드를 인위적으로 동기화하거나 비슷합니다.

만들기await이러한 메서드 호출은 오류가 발생한 위치를 더 잘 이해하는 데 도움이 됩니다.

나에게 효과가 있었던 암호는

describe("Some test set", () => {
  let heavyWorkingService = library.workingService();

   // We are marking the test function call as async
   test(("Name of the test"), async  () => {

     // we are awaiting heavyWorkingService to finish its job
     await heavyWorkingService("some data")
   })
})

실제 시나리오에서는 하지 않기 하고 있었습니다. 그리고 나는 이 테스트에 mock을 사용하지 않았기 때문에, 그것은 파이어베이스의 Import를 시도하고 있었다..get()데이터를 읽었습니다.의 마킹은 「」입니다」async 해서 합니다.await했습니다.

물론 이 오류에 대처하는 방법에는 여러 가지가 있습니다.이 오류의 진짜 원인을 알고 테스트에 적합한 솔루션을 사용할 수 있도록 해 주셨으면 합니다.

하고 .@testing-library/react-native가 한 은 '아예'입니다cleanup셋업 파일에 있습니다.

// jest.setup.js
import { cleanup } from '@testing-library/react-native';

afterEach(cleanup);

재담 테스트 파일의 맨 에 다음 행을 추가합니다. 결국 테스트는 작성됩니다.

afterAll(() => { 
  mongoose.connection.close()
})

한 번하나테스트 파일실행할 수 있습니다.예를 들어,

> jest --verbose --runInBand -- filename.test.js

위 중 어느 것도 나에게는 통하지 않는다.이 솔루션은 다음 코드를 jest-setup.js 파일에 추가하는 것입니다.

import { Animated } from 'react-native';

Animated.timing = () => ({
    start: () => jest.fn(),
});

패키지에 이 파일을 포함시키는 것을 잊지 마세요.json jajest 설정:

...
  "jest": {
    ...,
    "setupFiles": [
      "<rootDir>/src/tests/jest-setup.js"
    ]
  },
...

누구에게나 도움이 되었으면 좋겠다

jest.useFakeTimers사용 중인 다른 라이브러리의 실행을 방해하기 때문에 선택사항이 아니었습니다.

회피책은 각 테스트 후에 지연을 추가하여 Jest 환경이 해체되기 전에 비동기 조작을 완료할 수 있도록 하는 것이었습니다.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

describe('Test suite', () => {
  
  // Give time to any async operation to complete after each test
  afterEach(async () => {
    await sleep(2000);
  });

  // Also close any pending connection (or related) if any
  afterAll(async () => {
    await closeConnections();
  });

  it('My test', async () => {
    // Test...
  });
});

물론 지연 시간은 당신의 신청에 맞게 조정되어야 합니다.

아폴로호를 테스트하는 동안 이 문제가 발생했습니다.react-native-testing-library.

이 경우 부모 컴포넌트와 자녀 컴포넌트에 2개의 쿼리가 있습니다.하위 쿼리가 쿼리를 렌더링하고 실행하기 전에 상위 쿼리를 해결해야 했습니다.

해결방법은 다음 명령을 실행하는 것입니다.wait()한 번이 아니라 두 번 기능합니다.두 가지 쿼리를 모두 실행하려면 이중 공격이 필요하다고 생각합니다.에러 메세지는 매우 불투명합니다.

test("...", () => {
  const rr = render(...);
  await wait();
  await wait(); // Child query must also run
  expect(...);
}

// Wait a tick so the query runs
// https://www.apollographql.com/docs/react/development-testing/testing/#testing-final-state
export async function wait(ms = 0) {
  await act(async () => {
    return new Promise(resolve => {
      setTimeout(resolve, ms);
    });
  });
}

하고 @testing-library/react-native render(<MyComponent/>) 번 붙여야 요.afterEach(cleanup)그렇게 해서 문제를 해결했어요.

내 경우엔 타이포름을 사용하고 있었고 내 농담에 코드를 넣었다.셋업.ts

afterAll(async () => {
 const connection = getConnection();

 connection.close();
});

토론에 제 몫을 더하면...테스트 케이스에 비동기 코드가 있는지 다시 확인합니다.

내 경우는 기본적으로 주의력이 부족했다.

it('should not allow click', async () => {
    const page = await newE2EPage();
    await page.setContent(`<my-button disabled></my-button>`);

    const component = await page.find('my-button');

    // WRONG ! ! ! (since click() is async)
    component.click();

    // ✅ Correct
    await component.click()

    ...
  });

에러 메세지는 알기 쉬운 것은 아닙니다(적어도 저는 아닙니다).이게 누군가에게 도움이 됐으면 좋겠어!

추가해 보았다jest.useFakeTimers()내 안에beforeEach()방법을 사용했지만 문제가 해결되지 않았습니다.

이것.jest.mock()내 테스트 케이스 위에 있는 전화는 내게는 원인이었다.

jest.mock('axios', () => ({
    post: () => Promise.resolve({ data: 'data' }),
}));

삭제하면 문제가 해결됩니다.

이게 도움이 됐으면 좋겠네요.

패키지에 "test Environment" : "jsdom" 추가.제 경우엔 제이슨이 도움이 안 됐어요그런 다음 모든 Imports 아래에 테스트 파일을 추가했습니다.

jest.useFakeTimers();

첫 번째 테스트보다 위에 기재되어 있습니다.

  beforeEach(() => {
    jest.resetAllMocks();
  });

그래서 문제가 해결됐어요.

이 경우 오류는 자동으로 설명됩니다.

파티에 조금 늦었지만 난 단지 이 일로 여전히 어려움을 겪고 있는 사람을 돕고 싶을 뿐이야.에러가 나타내는 것처럼, 문제는, 코드의 일부가,import합니다.다음 코드를 확인합니다.

it('should do something', () => {
   someAsyncFuntion(); // We arent awaiting this function so the test ends before execution
});

const someAsyncFunction = async () => {
  const {getByPlaceholderText} = render(<SomeComponent />)

  getByPlaceholderText('Some placeholder text')
}

합니다.why for의 getByPlaceholderText「Import」의 「Import」의 「Import」의 「Import」의 「」를 으로 Import 하고 있는 것을 알 수 .TextInput★★★★★★★★★★★★★★★★★★:

const getTextInputNodeByPlaceholderText = (node, placeholder, options = {}) => {
  try {
    const {
      TextInput
    } = require('react-native'); // <--- Here we have our import

    const {
      exact,
      normalizer
    } = options;
    return (0, _filterNodeByType.filterNodeByType)(node, TextInput) && (0, _matches.matches)(placeholder, node.props.placeholder, normalizer, exact);
  } catch (error) {
    throw (0, _errors.createLibraryNotSupportedError)(error);
  }
};

알 수 있듯이 하고 있습니다.after이치노

이것을 joke.config.js에 추가합니다.

 timers: "fake",

이것은 이 문제를 해결하는 데 도움이 됩니다.

jeast.config.js 파일이 이렇게 표시됩니다.

module.exports = {
  preset: "react-native",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  transformIgnorePatterns: [
    "node_modules/(?!(@react-native|react-native|react-native-vector-icons)/)",
  ],
  timers: "fake",
};

Jest의 최신 버전에서는 이 버전을 사용합니다.

import type { Config } from "jest";

const config: Config = {
  preset: "react-native",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  testPathIgnorePatterns: [
    "/node_modules/",
    "<rootDir>/template",
    "Libraries/Renderer",
    "RNTester/e2e",
  ],
  transformIgnorePatterns: [
    "node_modules/(?!(@react-native|react-native|react-native-vector-icons)/)",
  ],
  fakeTimers: {
    enableGlobally: true,
  },
  verbose: true,
};

export default config;

내 프로젝트는 React Native 및 Type Scipt함께 진행됩니다.

디폴트로는 Jest 설정은 package.json 입니다.

이 문제를 해결하려면 "타이머"를 추가해야 했습니다. "짝퉁"

"jest": {
"timers": "fake",
"preset": "react-native",
"moduleFileExtensions": [
  "ts",
  "tsx",
  "js",
  "jsx",
  "json",
  "node"
]}

이것이 필요한 이유는 이미 설명되었습니다.

해체란 Jest 실행이 이미 완료되었으며 Jest 실행이 완료된 후 코드 일부가 실행하려고 시도하고 있음을 의미합니다.이것은 Javascript의 비동기 특성으로 인해 매우 일반적입니다.

테스트 환경(jsdom)을 추가할 필요가 없습니다.위에서 말한 것처럼, 리액트 네이티브에 대한 감각이 없다.

하였습니다.jest.useFakeTimers )의 ( )의beforeEach ) suit that file() 내

beforeEach(() => {
    jest.useFakeTimers();
  });

또는

jest.useFakeTimers() after ( 수 imports imports imports imports )

언급URL : https://stackoverflow.com/questions/50793885/referenceerror-you-are-trying-to-import-a-file-after-the-jest-environment-has

반응형