どうも、駆け出しエンジニアです
よくわからないことをとりあえずの備忘録で書いてます
今日はjsのテストをjestでやってみよう
今回はvueでモデルとしてjsを書いたのでそれのテストをしていきます
まずはjestの追加
yarnでjestを追加していきましょー
その他諸々も
yarn add jest babel-jest babel-core@^7.0.0-bridge.0 @babel/core @babel/preset-env
yarn add @babel/plugin-transform-modules-commonjs
.babelrcを作成。以下を追加
{
  "env": {
    "test": {
      "plugins": [ "@babel/plugin-transform-modules-commonjs" ]
    }
  }
}
最前面に__tests__フォルダ作成
その中にテスト関数を作っていきましょ
その前にchokidarでテストを保存したら自動で実行できるようにする
chokidar "__tests__/*.js" "*.js" -c "yarn jest"
今回するテスト
今回やっていくテストはvueでwebサイトを作ってるんですけど、
GASを使用して、google spread sheetからデータを持ってくるときのテストです
/* eslint-disable no-alert, no-console, no-undef */
import { User } from "../src/model/user";
describe("gasTest", () => {
  test("findByNum", async () => {
    let user = await User.makeUser("hogehoge");
    expect(user.id).toBe("hogehoge");
    expect(user.name).toBe("hoge");
  });
});
一応user.jsとbase.jsも乗っけておく
user.js
import { Base } from "./base";
export class User {
  constructor(array) {
    this.id = array[0];
    this.name = array[1];
    this.pass = array[2];
    this.ticket = parseInt(array[3]);
  }
  static makeUser(id) {
    return Base.findOne(id).then((array) => {
      return new User(array);
    });
  }
}
base.js
import fetch from "node-fetch";
export class Base {
  static URL() {
    return "https://script.google.com  //gasのurl";
  }
  static findOne(id) {
    return fetch(this.URL() + "?id=" + id)
      .then((response) => {
        return response.json();
      })
      .then((json) => {
        return json.flat();
        //返ってきたJsonファイルの各値を、表示するために代入。
      })
      .catch((err) => {
        console.log(err);
      });
  }
}
これで動いたし!!大丈夫そうかな!!
よし、寝るか!!
