LoginSignup
2
1

More than 3 years have passed since last update.

JestでHTML5 FileAPI を使ったテストをする方法

Posted at

概要

  • HTML5 FileAPIのFileオブジェクトを使ったテストをJestで行う方法について書きます

前提

  • Jestではフロントエンド アプリのテストもテスト時にNode.js用にコード変換して実行する
  • この特性のため、Node.js用にブラウザ用のAPIをがんばって再現してる(JSDOM等つかって)
  • なるべくNode.jsに媚びたコードを書かずフロントエンドのお作法だけでテストを書きたい

FetchしたファイルをHTML5 Fileとして取り扱う方法

やりたいこと

Fetch APIを使って、あるURLからファイルをダウンロードしてきて HTML5 File APIのFileオブジェクトとして取り扱い、それをJestしたい。

node-fetchをインストールする

フロントエンドでおなじみのFetch API (window.fetch) はNode.jsには無いので、似た機能を提供するnode-fetchをインストールする

npm install --save-dev node-fetch

fetchしたデータをHTML5 FileAPIのFileに変換して、それをJestする

コードは以下のとおり

import fetch from 'node-fetch';

describe('Fetch on Node', () => {

    test('Get HTML5 "File" on Node ', (done) => {

        const path = 'https://riversun.github.io/img/riversun_256.png';

        fetch(path)
            .then(res => {

                return res.arrayBuffer().then(buffer => ({
                    contentType: res.headers.get('Content-Type'),
                    buffer: buffer
                }));

            })
            .then(data => {
                return new File([data.buffer], path, {type: data.contentType});
            })
            .then(file => {

                console.log(`fileName=${file.name} fileSize=${file.size} fileType=${file.type}`);

                //Write some tests
                expect(true).toBe(true);

                done();

            });
    });
});

ポイントは以下のあたり。

node-fetchで取得したres.arrayBuffer()をバッファとしてnew File([バッファ])Fileを生成することができる。

(以前、こちらの記事で、ブラウザ上でフェッチしてFileを紹介したが、この方法はnode-fetchではうまくいかなかった。node-fetchblob()実装に何かありそう。)


 .then(res => {

                return res.arrayBuffer().then(buffer => ({
                    contentType: res.headers.get('Content-Type'),
                    buffer: buffer
                }));

            })
            .then(data => {
                return new File([data.buffer], path, {type: data.contentType});
            })

参考情報

ソースコード

紹介したコードを含む全ソースコードは https://github.com/riversun/jest_html5_file にあります

ソースコードの実行方法
npm clone https://github.com/riversun/jest_html5_file.git
npm instlal
npm test

Jestの設定ファイルなど

Jestの設定ファイルなどはこちらの記事と同様です

2
1
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
2
1