LoginSignup
1
0

More than 3 years have passed since last update.

スプレッド構文をJESTを書いて学習する

Last updated at Posted at 2019-09-05

はじめに

業務で React + TypeScript を触っていくことになった。

恥ずかしいことにスプレッド構文についてあまり良く知らなかったので下記の内容をJESTで検証しつつ学習した。

JESTを書いて学習する

spreadsyntax.spec.ts
describe('スプレッド構文', (): void => {

    describe('Array リテラルで使う', () => {

        test('Demo', () => {
            const sum = (x, y, z) => {
                return x + y + z;
            };
            const numbers = [1,2,3];
            expect(6).toBe(sum(...numbers));
            expect(6) .toBe(sum.apply(null, numbers))
        });

        test('引数の何番目でも使えるし、複数回使える', () => {
            function myFunction(v, w, x, y, z) {
                return [v, w, x, y, z];
            }
            const args = [0, 1];
            const actual = myFunction(-1, ...args, 2, ...[3]);
            expect([-1, 0, 1, 2, 3]).toEqual(actual);
        });

        test('すでにある配列を一部として新しい配列を作成', () => {
            const parts = ['shoulders', 'knees'];
            const lyrics = ['head', ...parts, 'and', 'toes'];
            expect(['head', 'shoulders', 'knees', 'and', 'toes']).toEqual(lyrics)
        });

        test('配列を複製する', () => {
            // 配列の複製
            const arr = [1, 2, 3];
            const arr2 = [...arr];
            expect([1,2,3]).toEqual(arr2)
        });

        test('Array を連結する', () => {
            const arr1 = [0, 1, 2];
            const arr2 = [3, 4, 5];
            expect([0,1,2,3,4,5]).toEqual([...arr1, ...arr2]);
        });
    });

    describe('Object リテラルで使う', () => {

        test('オブジェクトのマージ', () => {
            const obj1 = { foo: 'bar', x: 42 };
            const obj2 = { foo: 'baz', y: 13 };
            expect(obj1).toEqual({ ...obj1 });
            expect({ foo: "baz", x: 42, y: 13 })
                .toEqual({ ...obj1, ...obj2 });
        });

        test('Object.assign() 関数を置き換えたり模倣することはできない', () => {
            const obj1 = { foo: 'bar', x: 42 };
            const obj2 = { foo: 'baz', y: 13 };
            const merge = ( ...objects ) => ( { ...objects } );

            const exp1 = { 0: obj1, 1: obj2};
            expect(exp1).toEqual(merge( obj1, obj2));

            const exp2 = { 0: {}, 1: obj1, 2: obj2};
            expect(exp2).toEqual(merge({}, obj1, obj2));
        });
    });
});

ユニットテストを書きながら言語機能を学ぶのは理にかなっている。
フロントエンドもやっていくぞ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0