Upgrade to Pro — share decks privately, control downloads, hide ads and more …

jest introduction

jest introduction

Ryota Matsunaga

December 07, 2020
Tweet

More Decks by Ryota Matsunaga

Other Decks in Programming

Transcript

  1. "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
  2. 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) どこのテストが失敗したか教えてくれ る時もある
  3. 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; }; こういう関数があったとします
  4. 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を使ったテストはこんな感じ
  5. 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); }); });
  6. 複雑な関数を分解してテスト 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);