質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Babel

Babelは、JavaScriptの次世代仕様であるECMAScriptのコンパイラ。次世代の標準機能を用いて記述されたコードを、それらの機能に対応していないブラウザでも動作するコードに変換することができます。

Jest

Jestは、JavaScriptのテストフレームワークです。設定が不要で、高速且つ安全にテストを開始できます。コードカバレッジを生成できる他、テストスコープ外のオブジェクトを容易にモック化できるなど、豊富な機能によりテストの導入を簡単にします。

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Q&A

解決済

2回答

1317閲覧

引数を取る関数のテストで必ずエラーが発生している

sahksas

総合スコア28

Babel

Babelは、JavaScriptの次世代仕様であるECMAScriptのコンパイラ。次世代の標準機能を用いて記述されたコードを、それらの機能に対応していないブラウザでも動作するコードに変換することができます。

Jest

Jestは、JavaScriptのテストフレームワークです。設定が不要で、高速且つ安全にテストを開始できます。コードカバレッジを生成できる他、テストスコープ外のオブジェクトを容易にモック化できるなど、豊富な機能によりテストの導入を簡単にします。

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

0グッド

0クリップ

投稿2022/10/31 06:50

編集2022/10/31 06:57

概要

テスト対象の関数に引数を定義するとSyntaxErrorでテストが失敗します。

Typescript, Jestでテストを書いています。
ある、関数をテストするためにテストコードを書いたのですが、なぜかSyntaxErrorで失敗します。
ほとんど同じ内容で、関数から引数を除くと成功します。

詳細

失敗するコード

hoge.ts

ts

1const hoge = (huga: number) => { // ←引数hugaを設定 2 return 99999; 3}; 4 5export default hoge;

hoge.test.ts

ts

1import hoge from "./hoge"; 2 3test("hoge", () => { 4 const hage = hoge(1); // ←hogeに引数を与えると失敗 5 expect(hage).toBe(99999); 6});

成功するコード

hoge.ts

ts

1const hoge = () => { // ←引数なし 2 return 99999; 3}; 4 5export default hoge;

hoge.test.ts

ts

1import hoge from "./hoge"; 2 3test("hoge", () => { 4 const hage = hoge(); // ←hogeに引数を与えないと成功 5 expect(hage).toBe(99999); 6});

エラー内容

bash

1$ jest hoge.test.ts 2 FAIL hoge.test.ts 3 ● Test suite failed to run 4 5 SyntaxError: /Users/****/Doc/****/hoge.ts: Unexpected token, expected "," (1:18) 6 7 > 1 | const hoge = (huga: number) => { 8 | ^ 9 2 | return 99999; 10 3 | }; 11 4 | 12 13 > 1 | import hoge from "./hoge"; 14 | ^ 15 2 | 16 3 | test("hoge", () => { 17 4 | const hage = hoge(1); 18 19 at instantiate (node_modules/@babel/parser/src/parse-error/credentials.ts:62:21) 20 at instantiate (node_modules/@babel/parser/src/parse-error.ts:60:12) 21 at Parser.toParseError [as raise] (node_modules/@babel/parser/src/tokenizer/index.ts:1474:19) 22 at Parser.raise [as unexpected] (node_modules/@babel/parser/src/tokenizer/index.ts:1520:16) 23 at Parser.unexpected [as expect] (node_modules/@babel/parser/src/parser/util.ts:149:28) 24 at Parser.expect [as parseParenAndDistinguishExpression] (node_modules/@babel/parser/src/parser/expression.ts:1754:14) 25 at Parser.parseParenAndDistinguishExpression [as parseExprAtom] (node_modules/@babel/parser/src/parser/expression.ts:1162:21) 26 at Parser.parseExprAtom [as parseExprSubscripts] (node_modules/@babel/parser/src/parser/expression.ts:722:23) 27 at Parser.parseExprSubscripts [as parseUpdate] (node_modules/@babel/parser/src/parser/expression.ts:699:21) 28 at Parser.parseUpdate [as parseMaybeUnary] (node_modules/@babel/parser/src/parser/expression.ts:661:23) 29 at Parser.parseMaybeUnary [as parseMaybeUnaryOrPrivate] (node_modules/@babel/parser/src/parser/expression.ts:399:14) 30 at Parser.parseMaybeUnaryOrPrivate [as parseExprOps] (node_modules/@babel/parser/src/parser/expression.ts:411:23) 31 at Parser.parseExprOps [as parseMaybeConditional] (node_modules/@babel/parser/src/parser/expression.ts:366:23) 32 at Parser.parseMaybeConditional [as parseMaybeAssign] (node_modules/@babel/parser/src/parser/expression.ts:306:21) 33 at parseMaybeAssign (node_modules/@babel/parser/src/parser/expression.ts:260:12) 34 at Parser.callback [as allowInAnd] (node_modules/@babel/parser/src/parser/expression.ts:3084:16) 35 at Parser.allowInAnd [as parseMaybeAssignAllowIn] (node_modules/@babel/parser/src/parser/expression.ts:259:17) 36 at Parser.parseMaybeAssignAllowIn [as parseVar] (node_modules/@babel/parser/src/parser/statement.ts:1387:16) 37 at Parser.parseVar [as parseVarStatement] (node_modules/@babel/parser/src/parser/statement.ts:1049:10) 38 at Parser.parseVarStatement [as parseStatementContent] (node_modules/@babel/parser/src/parser/statement.ts:449:21) 39 at Parser.parseStatementContent [as parseStatement] (node_modules/@babel/parser/src/parser/statement.ts:359:17) 40 at Parser.parseStatement [as parseBlockOrModuleBlockBody] (node_modules/@babel/parser/src/parser/statement.ts:1241:25) 41 at Parser.parseBlockOrModuleBlockBody [as parseBlockBody] (node_modules/@babel/parser/src/parser/statement.ts:1216:10) 42 at Parser.parseBlockBody [as parseProgram] (node_modules/@babel/parser/src/parser/statement.ts:215:10) 43 at Parser.parseProgram [as parseTopLevel] (node_modules/@babel/parser/src/parser/statement.ts:197:25) 44 at Parser.parseTopLevel [as parse] (node_modules/@babel/parser/src/parser/index.ts:45:10) 45 at parse (node_modules/@babel/parser/src/index.ts:67:38) 46 at parser (node_modules/@babel/core/src/parser/index.ts:28:14) 47 at parser.next (<anonymous>) 48 at normalizeFile (node_modules/@babel/core/src/transformation/normalize-file.ts:43:18) 49 at normalizeFile.next (<anonymous>) 50 at run (node_modules/@babel/core/src/transformation/index.ts:38:23) 51 at run.next (<anonymous>) 52 at transform (node_modules/@babel/core/src/transform.ts:29:17) 53 at transform.next (<anonymous>) 54 at evaluateSync (node_modules/gensync/index.js:251:28) 55 at sync (node_modules/gensync/index.js:89:14) 56 at fn (node_modules/@babel/core/src/errors/rewrite-stack-trace.ts:97:14) 57 at transformSync (node_modules/@babel/core/src/transform.ts:66:10) 58 at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:521:31) 59 at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:648:40) 60 at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:700:19) 61 at Object.<anonymous> (hoge.test.ts:1:1) 62 63Test Suites: 1 failed, 1 total 64Tests: 0 total 65Snapshots: 0 total 66Time: 0.441 s 67Ran all test suites matching /hoge.test.ts/i. 68error Command failed with exit code 1. 69info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

補足情報

./jest.config.js, ./jest.setup.jsはそれぞれ作っていません。

./babel.config.jsをいじっています。

./babel.config.js

js

1module.exports = { 2 presets: [ 3 [ 4 "@babel/preset-env", 5 { 6 modules: "false", 7 useBuiltIns: "usage", 8 targets: "> 0.25%, not dead", 9 }, 10 ], 11 ], 12 env: { 13 test: { 14 presets: [["@babel/preset-env", { targets: { node: "current" } }]], 15 }, 16 }, 17};

もともと、./babel.config.jsを作らずにテストを実行していたのですが、下記エラーが発生するのでggってこれを追加しました。
正直この辺はよくわかっていません。
どちらのエラーもimportでコケているので、ここに問題があるのではないかと思っています。

bash

1$ jest hoge.test.ts 2 FAIL hoge.test.ts 3 ● Test suite failed to run 4 5 Jest encountered an unexpected token 6 7 Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. 8 9 Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration. 10 11 By default "node_modules" folder is ignored by transformers. 12 13 Here's what you can do: 14 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it. 15 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript 16 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. 17 • If you need a custom transformation specify a "transform" option in your config. 18 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. 19 20 You'll find more details and examples of these config options in the docs: 21 https://jestjs.io/docs/configuration 22 For information about custom transformations, see: 23 https://jestjs.io/docs/code-transformation 24 25 Details: 26 27 /Users/****/Doc/****/hoge.test.ts:1 28 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import hoge from "./hoge"; 29 ^^^^^^ 30 31 SyntaxError: Cannot use import statement outside a module 32 33 at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1422:14) 34 35Test Suites: 1 failed, 1 total 36Tests: 0 total 37Snapshots: 0 total 38Time: 0.224 s 39Ran all test suites matching /hoge.test.ts/i. 40error Command failed with exit code 1. 41info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

その他

  • hoge.ts自体に不具合はありません。
  • 関数hogeの中でhugaが使われていないことについては、今回の不具合とは関係ないと理解しています。(質問用のコードです。)
  • hugaをstringなど別の型に変えても同様のエラーが発生しています。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

sahksas

2022/10/31 07:14

`import hoge from "./hoge";`を`const hoge = require("./hoge");`に変えて見ましたが、やはり同様のエラーが発生しました。
guest

回答2

0

原因

ts-jestのインストールと設定が漏れていたことが原因。

解決方法

bash

1yarn add -D ts-jest

jest.config.js

js

1module.exports = { 2 transform: { 3 "^.+\\.(ts)$": "ts-jest", 4 }, 5};

投稿2022/10/31 08:50

sahksas

総合スコア28

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

JestのテストコードをTypeScriptに対して書く場合、ts-jestなどでTypeScript対応を行う必要があります。

引数がない場合は、そのままJavaScriptと解釈しても矛盾しないためテストが通っていただけです。

投稿2022/10/31 08:00

maisumakun

総合スコア145183

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

sahksas

2022/10/31 08:48

ありがとうございます! 無事解決いたしました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問