https://lealog.hateblo.jp/entry/2017/11/16/172815

og-image-1500.png

JestいいですよねJest。 あれこれプラグインとかライブラリとか入れなくてもだいたいのことができて。

さて、この1ヶ月くらいひたすらJestでテストを書き続けて、ハマったとこをメモ。 逆に言えば、ここに書いてないことでは一切困ってなくて、Jest最高って感じ。

Karmaみたいなブラウザでテストする機能さえつけばもう一生ついていきます感すらある。

before / afterでもasync

Docsにそれらしいコードはないけどできる。

beforeAll(done => {
  // some async tasks
  done();
});
beforeEach(async () => {
  await asyncTask();
});
afterEach(async done => {
  await asyncTask();
  asyncTask2(done);
});
afterAll(() => {
  // some sync tasks
});

Mochaとかだとbefore / afterやけど、JestはbeforeAll / afterAllである。

Matcherあれこれ

toHavePropertyのキー

const obj = {
  arr: [
    { x: 1 },
    { x: 2 },
  ],
  'hyp-hen': 'Hello'
};

expect(obj).toHaveProperty('arr.1.x', 2);
expect(obj).toHaveProperty('hyp-hen', 'Hello');

ってな感じで数値なプロパティもそのまま書けばいい。 ハイフンも気にせず書ける。

toHaveBeenCalledWith

const spy = jest.fn();
spy(1);
spy(3);
spy(5);

expect(spy).toHaveBeenCalledWith(3);
expect(spy).toHaveBeenCalledWith(5);
expect(spy).toHaveBeenCalledWith(1);

続けて呼べば次のmock.callsを見てくれる・・のではなく、そのモックがテストを通してその引数で呼ばれたかどうかがわかる(順不同)。 どれかひとつでも呼ばれてれば、パスする。

mockReturnValuemockImplementation

const foo1 = jest.fn().mockReturnValue('foo');
const foo2 = jest.fn().mockImplementation(() => 'foo');

この2つは同じではないことに気づかずドハマりしてた。mockReturnValue()のほうが短く書けていいやん、と。