Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
jest introduction
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Ryota Matsunaga
December 07, 2020
Programming
200
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
jest introduction
Ryota Matsunaga
December 07, 2020
Transcript
32 slides
Jest 松永遼太
話すこと Jest について 話なさないこと youtubeチャンネル
Jest とは
JavaScript のテスティングフレームワーク TypeScript, Node, React, Angular, Vue, Babel などに対応 テストがシンプルにできる
インストールする際は
https://jestjs.io/docs/ja/getting-started
"name": ”reverseInt_test", "version": "1.0.0", "main": "app.js", "scripts": { "test": "jest"
}, "author": "", "license": "ISC", "devDependencies": { "jest": "^24.9.0" }, "dependencies": {}, "description": "" Package.json
npm run test / yarn testでテストを実⾏できる
PASS ./reverseInt.test.js ✓ reverseIntのユニットテスト (6ms) Test Suites: 1 passed, 1
total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.816s, estimated 2s Ran all test suites. FAIL ./reverseInt.test.js ✕ reverseIntのユニットテスト (3ms) どこのテストが失敗したか教えてくれ る時もある
Matchers
Jest では、matcher を使⽤して、様々な⽅法で値のテストをする ことができます。 この時に使われる関数は test expect toBeなど
var reverseInt = function(x) { if (x === 0) return
0; const sign = (x > 0) ? 1 : -1; if (x < 0){ x = x * -1; } let reversedInt = 0; while(x > 0){ reversedInt = (reversedInt * 10) + (x % 10); x = Math.floor(x/10); } return reversedInt * sign; }; こういう関数があったとします
test('reverseIntのユニットテスト', () => { expect(reverseInt(0)).toBe(0); expect(reverseInt(3)).toBe(3); expect(reverseInt(51)).toBe(15); expect(reverseInt(300)).toBe(3); expect(reverseInt(123456789)).toBe(987654321); expect(reverseInt(-311)).toBe(-113);
//他にも expect(reverseInt(null)).toBeNull(); expect(reverseInt(true)).toBeTruthy(); expect(reverseInt(5)).toBeDefined(); expect(reverseInt(false)).toBeFalsy(); }); Jestでmatcherを使ったテストはこんな感じ
expect は “expectation” オブジェクトを返します。 toBeはObject.isを使って値を⽐べている expect(2 + 2).toBe(4)
じゃーオブジェクト同⼠を⽐べるには? const user = {name: “Ryota”,}; user[‘age'] = 20; expect(user).toEqual({name:
Ryota, age: 20});
⾮同期
⾮同期動のコードがある場合は Jestはテスト対象のコードがいつ 完了したかを別のテストに進む前に知る必要があります。 そのためにdone( )などの関数があります。 *Done を使うのはcallback を使って⾮同期をしている場合 https://jestjs.io/docs/ja/asynchronous
Async/ await を使おう
⾮同期のコードをテストする場合はjavascript でも使う async/await を使ったほうがシンプル test(‘the data is peanut butter’, async
() => { const data = await fetchData(); expect(data).toBe('peanut butter’); });
テストの構成
テストを実⾏する前にいくつかのセットアップ作業をしたり、テ ストが終了した後にいくつかの仕上げ作業をしたい場合がありま す
例えば、テストの前にデータベースを初期化し、テスト後はデータベースのデータを削除 しい
beforeEach(() => { initializeDatabase(); }); afterEach(() => { clearDatabase(); });
});
スコープ
describe('matching cities to foods', () => { beforeEach(() => {
return initializeFoodDatabase(); }); test('Vienna <3 sausage', () => { expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true); }); test('San Juan <3 plantains', () => { expect(isValidCityFoodPair(‘San Juan’, 'Mofongo')).toBe(true); }); });
describe ブロックの中にあるときは、 before などが ある場合 、 describe はdescribe ブロックの中のテストにだけに適⽤されます
モック関数
モック関数を使えば、複雑なコードも分解してテストできる
複雑な関数を分解してテスト const mockCallback = jest.fn(x => 42 + x); forEach([0,
1], mockCallback); expect(mockCallback.mock.calls.length).toBe(2); expect(mockCallback.mock.calls[0][0]).toBe(0); expect(mockCallback.mock.calls[1][0]).toBe(1); expect(mockCallback.mock.results[0].value).toBe(42);
コードにテスト⽤の値を⼊れるのにも利⽤できます const myMock = jest.fn(); myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true); console.log(myMock(), myMock(), myMock(), myMock());
// 10, 'x', true, true
Jest 応⽤編 Coming up next ……
https://jestjs.io/ja/
More Decks by Ryota Matsunaga
See All by Ryota Matsunaga
jest introduction
mats0000
0
300
Other Decks in Programming
See All in Programming
AWS CDKを理解するために公式の定義を深掘って解説してみる / Understanding AWS CDK by Digging into Its Official Definition
akihisaikeda
3
350
手の動かし方がわからなかった私が個人開発者になるまで
usagi0920_pochi
0
340
ローカルLLMの基本と近況 2611 / Local LLM basics and recent situation 2611
kishida
3
670
Growing PicoRuby's Ecosystem on ESP32
yuuu
2
150
社内AIエージェント「Askワンバン」における コストチューニングの取り組み
t0yohei
0
180
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
190
AIコーディングをセッションで終わらせない: PHPライブラリ開発におけるコンテキスト承継設計
ickx
0
110
Debian JP Projectのサーバー構成
uwabami
1
180
マルチプロダクトSaaSの アプリ一覧を速くする——複数プロダクトにまたがる「権限行脚」を減らすまで #techramen26conf
mktakuya
1
250
Promiseの向こう側へコンテキストを届ける ― proposal-async-context
seriseri
0
440
AppFunctionsの内部実装を紐解く
hiroaki404
1
120
Skills Are the New npm [AAIF Bengaluru, Nov 2026]
shivamsaraswat
0
140
Featured
See All Featured
Designing for Performance
lara
612
70k
AI Search: Where Are We & What Can We Do About It?
aleyda
0
8.3k
Winning Ecommerce Organic Search in an AI Era - #searchnstuff2025
aleyda
2
2.2k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.7k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
31
3.4k
Raft: Consensus for Rubyists
vanstee
143
7.9k
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
680
The Art of Programming - Codeland 2020
erikaheidi
57
15k
The Illustrated Children's Guide to Kubernetes
chrisshort
51
53k
How STYLIGHT went responsive
nonsquared
100
6.4k
Practical Orchestrator
shlominoach
192
12k
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
560