터미널에서 Jest 테스트를 디버깅하는 7가지 방법
console.log()
가 아닙니다.사진 제공: Nikola Đuza on Unsplash
1. 표준 방식
If you search Jest docs for a way to do it, it will tell you the following:
- Go to a Chromium-based browser and open
chrome://inspect
. - Click “Open dedicated DevTools for Node” like in the screenshot below:
- Put a
debugger
statement somewhere in your code (testing or production one). - Run
node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here]
.
And voilà, your tests should run and stop at the debugger in the DevTools you opened in step 2. Actually, the process will be stopped as soon as you run it because of the --inspect-brk
, but we will get to that later.
Often in projects, you are not using the raw Jest command. Sometimes it is wrapped in some other library, or uses some extra configuration to get it started. If that is the case with you, let’s dive in and find out different ways to debug and inspect our tests.
💡 Leave the dedicated DevTools for Node window open as we follow through other ways of debugging.
2. 초기 중단 없이
If you take a look, most of the magic here is done by the Node Inspector. What is cool about the Node Inspector is that when you donode --inspect
, a Node.js process listens for a debugging client on 127.0.0.1:9229
. This change got introduced in 2016. 누구나 쉽게 프로세스를 검사할 수 있습니다.이전 섹션의 예에서는
node --inspect-brk ...
를 사용했습니다. --inspect-brk
플래그를 사용하면 사용자 코드가 시작되기 전에 중단됩니다. 내 경우에는 테스트가 시작되자마자 중단되는 것을 신경 쓰지 않고 그냥 일반node --inspect
에 의지했습니다. node --inspect
는 실행 즉시 중단되는 대신 debugger
를 놓은 위치에서 중단됩니다. 지금부터 그것으로 움직이자. 디버깅 명령은 다음과 같습니다.$ node --inspect node_modules/.bin/jest --runInBand
node_modules
위치는 운영 체제에 따라 달라질 수 있으므로 불가지론적으로 만들고 yarn bin
또는 npm bin
를 사용할 수 있습니다. 제 경우에는 다음과 같이 npm bin
를 사용하겠습니다.$ node --inspect $(npm bin)/jest --runInBand
3. TypeScript 테스트 디버깅
If you are using TypeScript these days, if you try to run:
$ node --inspect $(npm bin)/jest --runInBand
You might get an error because TypeScript tests are not transpiled to JavaScript. Make sure you configured Jest in jest.config.js
similar to the following configuration:
module.exports = {
roots: ["<rootDir>/src"],
testMatch: [
" **/ __tests__ /** /*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest", // The important part right here
},
}
.ts
and .tsx
files using ts-jest
. If you don’t have ts-jest
, you can install it with npm install -D ts-jest
, and you should be good to go. I made a sample repo where you can try it out right here .4. 디버그하는 가장 좋은 방법 ™️
OK, so the title of this section promises a lot, and bear with me. If you didn’t hear about Jest watch mode, you are going to love this. Most of the time I am writing code, I have jest --watch
running. What is excellent about the watch mode is that it will watch for any changes you made, and run the related tests. To debug your tests in watch mode, you can type the following:
$ node --inspect $(npm bin)/jest --watch --no-cache --runInBand
Let’s break down the Jest arguments a bit here:
-
--watch
launches the watch mode from Jest, which is pretty cool. -
--no-cache
will make sure our code is properly reloaded. You can try without it, but the watch mode might not work properly. -
--runInBand
- OK, this flag has been following us from the start. It is there to make sure all tests run serially in one process instead of creating child processes. Having one process makes it possible fornode --inspect
to “inspect” tests properly.
You can also combine other Jest commands like running a single test:
$ node --inspect $(npm bin)/jest --runTestsByPath src/index.test.ts --runInBand
But do not forget to attach the --runInBand
or just -i
to make sure the Node.js inspector works its magic.
5. CRA는 어떻습니까?
If you use create-react-app (CRA) and have your test script use react-scripts test, debugging will be a bit different for you. A recommended way is to add a new script to package.json
like so:
"scripts": {
...,
"test:debug": "react-scripts --inspect test --runInBand --no-cache"
}
Now, whenever you run npm run test:debug
, the Jest will run in watch mode and stop in the place where you put debugger
. Of course, you need to have a dedicated DevTools for Node.js open, as we described in the first section.
6. 명령줄에서 디버깅
OK, so you got the initial debugger working with Chromium-based browser and DevTools. But, if you are a command-line aficionado, you probably are thinking of a way to do it without the DevTools. Good news for you, it can be done. Luckily, we have node inspect
to launch a command-line debugger for us. Try running just the following command:
$ node inspect $(npm bin)/jest --runInBand
I ran this in the example repo I made, and this is what I got:
$ node inspect $(npm bin)/jest --runInBand
< Debugger listening on ws://127.0.0.1:9229/be2d3410-48ad-46fb-a345-bb37339b5e38
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in node_modules/jest/bin/jest.js:9
7 */
8
> 9 const importLocal = require('import-local');
10
11 if (!importLocal(__filename)) {
debug>
The inspector stopped at the first line inside node_modules/jest/bin/jest.js:9
. We can go ahead and continue the debugger by typing cont
or just c
:
$ node inspect $(npm bin)/jest --runInBand
< Debugger listening on ws://127.0.0.1:9229/be2d3410-48ad-46fb-a345-bb37339b5e38
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in node_modules/jest/bin/jest.js:9
7 */
8
> 9 const importLocal = require('import-local');
10
11 if (!importLocal(__filename)) {
debug> cont
break in src/index.test.ts:6
4 test("add", function () {
5 var result = index_1.add(1, 2);
> 6 debugger;
7 expect(result).toEqual(3);
8 });
debug>
Now the inspector stopped at the debugger
statement in our test code. We can type help
and get acquainted with all the commands we can type there. I won’t go over all of them, but I will mention the repl
command. By typing the repl
while inside the debugger, you will enter the Read-Eval-Print-Loop (REPL) mode, where you can evaluate variables. If I do that in my example, I will get the following:
$ node inspect $(npm bin)/jest --runInBand
< Debugger listening on ws://127.0.0.1:9229/be2d3410-48ad-46fb-a345-bb37339b5e38
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in node_modules/jest/bin/jest.js:9
7 */
8
> 9 const importLocal = require('import-local');
10
11 if (!importLocal(__filename)) {
debug> cont
break in src/index.test.ts:6
4 test("add", function () {
5 var result = index_1.add(1, 2);
> 6 debugger;
7 expect(result).toEqual(3);
8 });
debug> repl
Press Ctrl + C to leave debug repl
> result
3
>
And those are the basis of inspecting your code from the command-line. The developer experience (DX) might not be as great as the one with DevTools open, where you can get values of variables by hovering over them, but it’s still a nice alternative. Let’s see how we can open DevTools from the command line in the next section.
7. 올인원 솔루션 - ndb
ndb is a library for improving the debugging experience for Node.js. You can install it globally withnpm install -g ndb
or locally with npm install -D ndb
. I tried it on my Abacus repo 전역 명령은 다음과 같습니다.$ ndb $(npm bin)/jest --watch --no-cache --runInBand
그리고 그것은 훌륭하게 작동합니다. 입력하자마자 DevTools가 열립니다. 또한 일반보다 더 빠르게 수행되었습니다
node --inspect
. ndb의 장점은 package.json
에 대한 스크립트를 쉽게 실행할 수 있다는 것입니다. 나는 다음을 실행했습니다.$ ndb npm run test -- --watch --no-cache --runInBand
나는 ndb를 사용하는 접근 방식이 명령줄에서 모든 작업을 수행하려는 사람들에게 가장 매력적이라고 생각합니다. Node.js용 DevTools를 열기 위해 브라우저로 이동하지 않아도 됩니다. ndb가 대신해 드립니다.
마지막 생각들
That’s it for now, folks. You should be able to pick and choose a way to debug your Jest tests. The idea of debugging tests in Jest was “bugging” me for quite some time, and I am happy I found various solutions and that I get to share them with y’all.
Thanks for tuning in, and be sure to subscribe to the and follow me on for new blog posts and tips. If you find the post useful, consider sharing it on Twitter with your friend and co-workers:
pragmaticpineapple.com/7-ways-to-debu…
오전 08:51 - 2021년 3월 15일
다음 편까지, 건배.
Reference
이 문제에 관하여(터미널에서 Jest 테스트를 디버깅하는 7가지 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nikolalsvk/7-ways-to-debug-jest-tests-in-terminal-20am텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)