https://lealog.hateblo.jp/entry/2017/11/16/172815
JestいいですよねJest。 あれこれプラグインとかライブラリとか入れなくてもだいたいのことができて。
さて、この1ヶ月くらいひたすらJestでテストを書き続けて、ハマったとこをメモ。 逆に言えば、ここに書いてないことでは一切困ってなくて、Jest最高って感じ。
Karmaみたいなブラウザでテストする機能さえつけばもう一生ついていきます感すらある。
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
である。
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
を見てくれる・・のではなく、そのモックがテストを通してその引数で呼ばれたかどうかがわかる(順不同)。
どれかひとつでも呼ばれてれば、パスする。
mockReturnValue
とmockImplementation
const foo1 = jest.fn().mockReturnValue('foo');
const foo2 = jest.fn().mockImplementation(() => 'foo');
この2つは同じではないことに気づかずドハマりしてた。mockReturnValue()
のほうが短く書けていいやん、と。