2023年3月11日 星期六

原始碼解析 create-vue 快速建立 Vue 專案


Vue 可以透過下面的指令,接著詢問一系列的問題,按照設定快速初始一個專案。(目前版本為 3.6.1)

npm init vue@latest

實際是執行這個 create-vue,想透過原始碼的解析,來了解怎麼樣做一個類似的功能,這個專案架構是如何、如何達成建立專案的功能。


1. playground

運用 git submodules的功能,主要是將各種條件下的樣板做snapshot,形成另一個 create-vue-templates 專案。


2. scripts

顧名思義分別對應到 package.json 的 scripts 所執行的檔案名。

  • build
  • prepublish
  • snapshot
  • test

3. template

將程式碼依照性質分成不同的目錄,根據使用者的設定將對應的檔案複製或合成等,形成 Vue 的專案。

  • base: 基本必備的程式碼,主要套件為 vue, vite
  • code: HelloWorld.vue 元件以及 vue-router 範例程式碼,會分成有無使用 ts 版本。
  • config: 裡面每個目錄依照套件名稱命名,目錄包含:cypress-ct, cypress, jsx, pinia, playwright, router, typescript, vitest,目錄裡是安裝套件的設定檔。主要會有 package.json 設定安裝那些套件,後續會將內容與現有設定合併,再來以 cypress 為例,會有 cypress.config.jscypress.config.ts,屆時會根據是否有用 ts 來複製對應的檔案。
  • entry: 指的是 vite 打包的 entry main.js,執行 createApp 的功能,總共有預設, pinia, router, pinia+router 這四種版本。
  • eslint
  • tsconfig

4. utils

目錄及檔案合併等方法都在這個目錄裡,檔名命名已經相當清楚。


5. index

主要邏輯在這個檔案

  • 讀 argv 指令
  • 使用 prompts 詢問一連串問題
  • 依照專案名稱等,產生 package.json
  • 複製 base
  • 複製 config
  • 複製 tsconfig
  • 產生 eslint
  • 複製 entry
  • 清除 js or ts 多餘的檔案或重新命名
  • 產生 README.md
  • 專案已完成,顯示指令提示

拆解過後,我覺得最重要的是如何整理出 template/,讓不同的安裝需求可以拆解出來,有秩序地組成這個初始的專案。


2023年1月27日 星期五

[Jest+Testing Library] Vue + storybook interaction 元件測試範例


storybook 可以獨立建立元件,並搭配 @storybook/addon-controls 控制 props 輸入及 @storybook/addon-actions 顯示 emit 輸出的內容,當然可以透過手動開啟 GUI 來測試元件是否符合規格,storybook 已經完成 render 的步驟,自動化的測試只差一步了!

storybook 可以搭配 interaction 套件進行元件測試,先按照「[Vue.js] storybook安裝方式與環境建置」完成 vue+storybook 的安裝,文內還是使用 Vue2,如果使用 Vue3 其實步驟差異不大。


安裝

執行指令

npm install --save-dev @storybook/addon-interactions @storybook/jest @storybook/testing-library


設定

請開啟 .storybook/main.js,註冊這個 addon interactions 套件,@storybook/addon-interactions 一定要放在 @storybook/addon-actions@storybook/addon-essentials 的後面。

module.exports = {
    addons: [
        '@storybook/addon-actions', // or '@storybook/addon-essentials'
        '@storybook/addon-interactions',
    ],
    features: {
        interactionsDebugger: true,
    },
};


撰寫測試

寫測試前,要先了解測試元件的重點是「邏輯!」

第一視覺的邏輯,經由 props 或 slots 改變元件顯示上的差異,例如文字內容或是決定是否顯示哪些區域等;第二行為的邏輯,當使用者輸入或點擊按鈕等,此時畫面產生的變化或是 emit 的事件內容等。

使用 jest + testing library 做測試,testing library底層為 vue test utils,兩者相比 testing library 可以更聚焦於元件測試,不容易因為非邏輯的變更,連同測試都要一起做調整。


簡單寫一個元件 NameEditor.vue,有兩個 props,按下按鈕可以發出 event。

<template>
    <div>
        <div
            v-text="message" />
        <input
            type="text"
            placeholder="name"
            v-model.trim="name">
        <button
            type="button"
            @click="onButtonClick"
            v-text="buttonText" />
    </div>
</template>

<script>
import {ref} from 'vue';

export default {
    props: {
        message: {
            type: String,
            required: true,
        },
        buttonText: {
            type: String,
            required: true,
        },
    },
    setup(props, {emit}) {
        const name = ref(undefined);

        const onButtonClick = () => {
            emit('subit', name);
        };

        return {
            name,
            onButtonClick,
        };
    },
};
</script>

接著,NameEditor.stories.js story基本的內容:

import {userEvent, screen} from '@storybook/testing-library';
import {expect} from '@storybook/jest';
import NameEditor from './NameEditor';

export default {
    title: 'NameEditor',
    argTypes: {
        message: {
            control: 'text',
        },
        buttonText: {
            control: 'text',
        },
        onNameSubmit: {
            action: 'submit',
        },
    },
};

const Template = (args, {argTypes}) => ({
    props: Object.keys(argTypes),
    components: {
        NameEditor,
    },
    template: `
        <NameEditor
            :message="message"
            :button-text="buttonText"
            @submit="onNameSubmit" />
    `,
});

export const Default = Template.bind({});

Default.args = {
    message: 'Input your name',
    buttonText: 'Submit',
};

interaction 的測試,必須寫在 play 裡面,測試流程是先輸入文字後,按下按鈕:

Default.play = async ({args}) => {
    const mockName = 'Chenuin';
    const button = screen.getByRole('button');

    await userEvent.type(screen.getByPlaceholderText('name'), mockName); // input name
    await userEvent.click(button); // click button

    const {message, buttonText, onNameSubmit} = args;

    expect(onNameSubmit).toHaveBeenCalledTimes(1);
    expect(onNameSubmit).toBeCalledWith(mockName);

    expect(screen.getByText(message)).toBeTruthy();
    expect(button.textContent).toBe(buttonText);
};

可以透過 args 取得 argTypes 的內容,發出的 event 自動 mock 可以直接驗證,只要把握 testing library獲取Dom的方式,需要注意 getBy...queryBy... 兩者差別,前者若取不到任何相符條件的element,會拋出exception,後者不會。其他部分就是 jest 語法。



執行

開啟 storybook 就會自動執行測試內容,如果有錯誤也會將訊息顯示畫面。

npm run storybook

(畫面如下)


到這邊就告一段落,如果希望能夠導入CI,可以使用 @storybook/test-runner

npm install --save-dev @storybook/test-runner

開啟 package.json 加入 npm script

{
  "scripts": {
    "test-storybook": "npx test-storybook"
  }
}

預設 test runner 會找到 http://localhost:6006 進行測試,可以加上 --url 來改變路徑。

npm run test-storybook

如果不是本地啟用storybook,可以利用 https://www.chromatic.com/ 來管理 storybook,就可以透過 internet 進行。Chromatic 可以用來發布 storybook、主要方便團隊 UI Review,藉此進行 CI 測試整合會更加容易。



參考資料

storybook 套件


2023年1月14日 星期六

第一個 Vue3 元件測試從 Vitest + Vue Test Utils 開始

延續「mocha + webpack 的 Vue3 元件單元測試」,既然使用 mocha 測試太卡關,這次安裝 Vitest 來試試看!

一、安裝

先安裝 Vitest,另外 Vitest 需要使用 Node >=v14,並安裝 Vite >=v3.0.0,還有 vue3 對應的測試套件

npm install --save-dev vite vitest @vue/test-utils @vitejs/plugin-vue

下面這幾個根據需求來選擇是否安裝

npm install --save-dev jsdom

提供UI介面,可參考 Test UI

npm install --save-dev @vitest/ui


二、設定

先到package.json設定npm指令

"scripts": {
    "test": "npx vitest",
}

在根目錄新增檔案 vitest.config.js

import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'

export default defineConfig({
    plugins: [
        Vue(),
    ],
    test: {
        globals: true,
        environment: 'jsdom',
    },
});

常用的設定像是include指定測試檔案的目錄或名稱等,和exclude排除檔案

export default defineConfig({
    test: {
        include: ['**/*.test.js'],
        exclude: ['**/node_modules/**'],
    },
});

設定路徑的alias

export default defineConfig({
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        },
    },
});

或者可以設定 csssetupFiles來套用css style

export default defineConfig({
    test: {
        css: true,
        setupFiles: './src/vitest/setup.js',
    },
});

src/vitest/setup.js import css

// src/vitest/setup.js

import 'todomvc-app-css/index.css';
import 'todomvc-common/base.css';

其他設定可以參考官方文件

完成基本設定後,就可以開始寫測試囉!



三、測試

針對現有的元件 TodoListEditor 撰寫測試

import { mount } from '@vue/test-utils';
import { test, expect } from 'vitest';
import TodoListEditor from 'components/TodoListEditor.vue';

test('TodoListEditor', () => {
    expect(TodoListEditor).toBeTruthy()

    const wrapper = mount(TodoListEditor, {
        props: {
            todoList,
        },
    });

    expect(wrapper.vm.todoList).toStrictEqual(todoList);
    expect(wrapper.props('todoList')).toStrictEqual(todoList);
});

參考資料



四、執行
npm run test

執行後就可以看到所有的測試項目及結果,若有錯誤也會對應的訊息顯示

有安裝@vitest/ui,可以開啟ui試試看

npm run test -- --ui


五、CI/CD

有了測試之後,我們利用 github action 設定每次 push 分支時,執行 vitest 的測試,請新增檔案 .github/workflows/test.yml

name: Test

on:
  push:
    branches: main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Before srcipt
        run: npm install

      - name: Test
        run: npm run test -- --run

.github/workflows/gh-pages.yml內的設定:

on:
  workflow_run:
    workflows: ["Test"]
    types:
      - completed

jobs:
  build:
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest

    steps:
      ....

我們的目標是當 Test 成功時,才會執行部屬,否則忽略。請注意 completed 指的是完成時,無論測試結果成功與否都會觸發。因此 if: ${{ github.event.workflow_run.conclusion == 'success' }} 的設定是必要的。

也可變化成 ${{ github.event.workflow_run.conclusion == 'failure' }},當測試結果失敗時可以發送通知,根據應用情境改寫。

workflows可以設定多項,只要有任何一項執行就會觸發。


安裝 Vitest 來進行 Vue3 測試十分容易。語法跟 jest 很相像,甚至原本的 mocha 寫的測試也一行都沒改,都能夠支援測試。以上的內容有上傳到 github 上(專案),可以點選下方連結了解執行的內容。


2022年9月28日 星期三

[E2E Testing] 如何從 cypress 9 升級 10

使用 cypress 進行 E2e Testing,針對比較常用的部分整理從 Cypress 9 升級到 10 一些異動,最大的差別是不再支援 cypress.json,並移除了 plugins 目錄。


安裝 cypress 10

npm install --save-dev cypress@10

如何升級至 cypress 10

主要針對 e2e 調整的部分進行說明,啟動 cypress 時,原本會讀取根目錄建立 cypress.json的設定,cypress 10不再支援。檔案格式可以支援 js/ts,底下範例以cypress.config.js為主,另外參數的設定也做出調整:

baseUrl

從設定在最上層,改成專屬 e2e 測試的設定,若只做 component testing 就不需要設定這個參數,讓 e2e / component testing 的設定更一目瞭然。

Before cypress.json
{
  'baseUrl': 'http://localhost:1234'
}
After cypress.config.js
const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:1234'
  }
});

pluginsFile

這個設定不需要,直接移除即可。

Before cypress.json
{
  'pluginsFile': 'cypress/plugins/index.js'
}

setupNodeEvents

移除 pluginsFile 的設定後,原本的內容也直接移到 cypress.config.js 進行設定,過去版本9若同時使用 component / e2e testing,可以將設定直接分開來寫。

Before cypress/plugins/index.js
module.exports = (on, config) => {
  if (config.testingType === 'component') {
    // component testing dev server setup code
    // component testing node events setup code
  } else {
    // e2e testing node events setup code
  }
};
After cypress.config.js
const { defineConfig } = require('cypress');

module.exports = defineConfig({
  component: {
    devServer(cypressConfig) {
      // component testing dev server setup code
    },
    setupNodeEvents(on, config) {
      // component testing node events setup code
    },
  },
  e2e: {
    setupNodeEvents(on, config) {
      // e2e testing node events setup code
    },
  },
});

完整內容請參考官網升級指引


相關文章:


2022年7月25日 星期一

Vue3.2 <script setup> 實作 TodoMVC


Vue3.2開始將 <script setup> 移除experimental status,和setup()區別在有許多 option API 有了替代方案,props, emit 也可以寫在 setup`,variable 或 function 也不需要透過 return 才能讓 <template> 使用,哇!寫法怎麼好像有點既是感呢

下面會利用 TodoMVC 的練習,比較與統整 <script setup>setup() 常用的方法的差異。

TodoMVC 完整程式碼上傳至 Github (連結)。

data

setup
<script>
import { ref } from 'vue';

export default {
    setup() {
        const newTodo = ref(undefined);

        return {
            newTodo,
        };
    },
}
</script>
<script setup>
宣告 ref 沒有差異,差在需不需要 return
<script setup>
import { ref } from 'vue';

const newTodo = ref(undefined);
</script>


component

<template>
    <TodoListEditor />
</template>
setup
<script>
import TodoListEditor from 'components/TodoListEditor.vue';

export default {
    components: {
        TodoListEditor,
    },
}
</script>
<script setup>
import 之後就可以直接在 <template> 使用
<script setup>
import TodoListEditor from 'components/TodoListEditor.vue';
</script>


props

setup
<script>
export default {
    props: {
        todoList: {
            required: true,
            type: Array,
        },
    },
}
</script>
<script setup>
defineProps 裡面內容與之前 props 相同
<script setup>
const props = defineProps({
    todoList: {
        required: true,
        type: Array,
    },
});
</script>


emit

setup
<script>
export default {
    emits: ['remove:todo', 'update:todo'],
    setupt(props, {emit}) {
        function removeTodoItem(id){
            emit('remove:todo', id);
        }
    },
}
</script>
<script setup>
defineEmits 裡面內容與之前 emits 相同
<script setup>
const emit = defineEmits(['remove:todo', 'update:todo']);

function removeTodoItem(id){
    emit('remove:todo', id);
}
</script>


directive

directive是所有寫法中我最不適應的,底下是頁面載入時可以有 autofocus 的效果,可以根據不同 lifecyle 定義,利如 mouted
<input
    v-model="newTodo"
    v-focus>
setup
<script>
const focus = {
    mounted: el => el.focus(),
};

export default {
    directives: {
        focus,
    },
}
</script>
<script setup>
<script setup>
const vFocus = {
    mounted: el => el.focus(),
};
</script>


lifecycle

基本上沒有什麼區別
setup
<script>
import {onMounted} from 'vue';

export default {
    setup() {
        onMounted(() => {
            // to something
        });
    },
}
</script>
<script setup>
<script setup>
import {onMounted} from 'vue';

onMounted(() => {
    // to something
});
</script>


2022年7月24日 星期日

mocha + webpack 的 Vue3 元件單元測試

先說結論,我認為不適合用 mocha 進行 vue3 單元測試(@vue/test-utils),反覆查了很久的資料,相關的套件支援度不足等有重重的障礙,根據 @vue/test-utils 目前提供的測試範例,選擇 Vitest 會更適合。

完整程式碼上傳至 Github (連結)。

一、安裝

首先,第一個問題就是 vue 的版本不能太新,目前只支援 3.0.7,因此對應安裝了相同版本的 @vue/server-renderer

npm install --save-dev @vue/server-renderer@3.0.7

再來請安裝 webpck 和 mocha,mochapack,mochapack 是用來讀取 webpack 設定將元件 render 出來的套件,可支援 webpack5 和 mocha 9

npm install --save-dev webpack mocha mochapack

其他有兩個類似的套件:

mochapack 是由 mocha-webpack 延伸而來的,三者用法都非常接近,但上述兩個對 webpack 和 mocha 版本的支援度都比 mochapack 差


再來請安裝 vue3 官方的元件測試套件 @vue/test-utils

npm install --save-dev @vue/test-utils

mocha 不像是 jest 已經內建支援 jsdom、assertion ,所以要另外安裝

npm install --save-dev webpack-node-externals jsdom-global
npm install --save-dev expect


二、設定

新增測試專用的 webpack 設定檔 webpack.config-test.js

// webpack.config-test.js

const nodeExternals = require('webpack-node-externals');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
    mode: 'development',
    target: 'node',  // webpack should compile node compatible code
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
    devtool: 'inline-cheap-module-source-map',
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    plugins: [
        new VueLoaderPlugin(),
    ],
};

設定 jsdom 設定檔 src/tests/setup.js

// src/tests/setup.js

require('jsdom-global')();

最後,請到 package.json 設定 script 指令

Usage: mochapack [options] [<file|directory|glob> ...]

Options
 --webpack-config  path to webpack-config file
 --require, -r     require the given module
{
  "scripts": {
    "test": "npx mochapack --webpack-config webpack.config-test.js --require src/tests/setup.js src/tests/**/*.spec.js",
  }
}


三、執行
新增測試(範例請參考 Counter.spec.js)後,執行指令即可
npm run test


四、限制

1. 無法支援目前 vue 最新版本 3.2.37,發現底下錯誤訊息:

ReferenceError: SVGElement is not defined

2. 無法支援 SFC ,發現底下警告訊息:

[Vue warn]: Component is missing template or render function.


參考文件:


2022年6月25日 星期六

【升版指南】Vue3 非兼容的特性 v-model 跟 Vue2 完全不一樣


vue2 v-model 的使用方式在這篇「[Vue.js] 如何在component自訂v-model」介紹,簡單說就是結合v-model其實綁定了名為 valuepropsinputemit事件,因此所謂的 v-model 就是一個父子元件的雙向溝通,在 vue2 兩者是相同的:

<input v-model="username">

<input :value="username"
       @input="(value)=>(username=value)">


但是!

vue3 props 預設名稱從 value 改為 modelValueemit 名稱則從 input 改為 update:modelValue,如果用錯了就無法達成雙向的綁定。

<input v-model="username">

<input :model-value="username"
       @update:modelValue="(value)=>(username=value)">

在 vue2 中可以用自訂 model 來自訂 propsemit 名稱,在 Vue3 移除不再支援,如果不想使用 modelValue 的話,在 Vue3 可以這樣寫:

<MyComponent v-model:username="username" />

<MyComponent
       :username="username"
       @update:username="(value)=>(username=value)" />

元件本身應該增加這個 props,更新時會呼叫 update:username

// MyComponent.vue
props: {
    username: {
        type: String,
        required: true,
    },
}

跟 vue2 .sync 有點相似,vue3不再支援 .sync ,寫法會是 v-model:[NAME] 後面 Name 就是想自訂的名稱,更新時update:[NAME],以事件名稱來看不算是完全客製,須按照規則觸發向上更新

但這個特性最棒的是支援多組 v-model ,你可以這樣寫:

<MyComponent
       v-model:username="username"
       v-model:password="password" />

總結將 vue2 升至 vue3,v-model 應該注意三個地方:

1. 不再使用 .sync

<MyComponent :username.sync="name" />

<!-- to be replaced with -->

<MyComponent v-model:username="name" />

2. 將所有的 value 和 input 和 modelValue 和 update:modelValue

<MyComponent v-model="name" />
// MyComponent.vue

export default {
  props: {
    modelValue: String, // "vaule" is replaced
  },
  emits: ['update:modelValue'],
  methods: {
    changeName(name) {
      this.$emit('update:modelValue', name);  // "input" is replaced
    },
  },
};

3. 不再使用 model

直接用 v-model ,v-model:[Name]


參考文章:https://v3-migration.vuejs.org/breaking-changes/v-model.html


2022年6月8日 星期三

Github Action 自動部署 github-pages


Github pages 適合展示靜態頁面,只要在 github 建立 gh-pages 分支,可依據用戶名稱和repo名稱來開啟頁面。

https://[USER_NAME].github.io/[REPO_NAME]/

以這個專案為例

https://github.com/chenuin/JavaScript30

路徑會是

https://chenuin.github.io/JavaScript30/


使用 JamesIves/github-pages-deploy-action@v4.3.3 有兩個必填參數:

  • branch: 分支
  • folder: 目錄,.代表整個repo根目錄

參數詳細說明請參考這裡,在 repo 裡新增 github action (連結):

name: Github pages

on:
  # Triggers the workflow on push events but only for the "master" branch
  push:
    branches: master

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout 🛎️
        uses: actions/checkout@v3

      - name: Deploy 🚀
        uses: JamesIves/github-pages-deploy-action@v4.3.3
        with:
          branch: gh-pages
          folder: .
          token: ${{ secrets.GH_PAT }}

GH_PAT 設定方式,請先至 Settings => Developer settings => Personal access tokens (或下方連結),按右上角新增Token,scopes 可直接勾選 repo 並將Token複製。

https://github.com/settings/tokens


再到專案的 Settings => Secrets => Actions (或下方連結),按右上角新增,命名 GH_PAT 並將剛剛複製的Token貼上。

https://github.com/[USER_NAME]/[REPO_NAME]/settings/secrets/actions


EASY!!


相關文章:


2022年5月28日 星期六

Vue3+jest 測試 composable 範例


Vue3 的 composable 乍看下和 mixin 用途很類似,可以提供各個元件共用程式碼。但與 mixin 相比,composable 主要有三個優勢:

第一,元件可以很明確的區分使用的 composable 來源,當使用的 mixin 一多時,追朔來源相對困難,無法一眼看出由哪個 mixin 實作。

第二,多個 mixin 無法確保使用了相同的名稱,可能造成覆蓋,但 composable 即使有相同的名稱,也能透過結構式賦值、重新命名。

最後,多個 mixin 需要交互作用時,通常會使用相同的參數命名來達到這個目的,隱性的耦合使得辨識和debug難度增加,composable可藉由其一的回傳值,作為其他composable輸入的參數達到共享的目的。(參考資料)


安裝 Jest 測試 vue 時,首先要注意版本,請參考下面的對照表安裝套件:

Vue version Jest Version npm Package

Vue 2 Jest 26 and below vue-jest@4

Vue 3 Jest 26 and below vue-jest@5

Vue 2 Jest 27 and above @vue/vue2-jest@27

Vue 3 Jest 27 and above @vue/vue3-jest@27

Vue 2 Jest 28 and above @vue/vue2-jest@28

Vue 3 Jest 28 and above @vue/vue3-jest@28


composable 的測試主要分成兩種,第一種元件比較無關,可以當作普通的 js code 測試。

// counter.js
import {ref} from 'vue';

export function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;

  return {
    count,
    increment,
  };
};
// counter.test.js
import {useCounter} from './counter.js';

test('useCounter', () => {
  const {count, increment} = useCounter()
  expect(count.value).toBe(0);

  increment();
  expect(count.value).toBe(1);
});

如果 composable 牽涉到元件 lifecyle hooks 或是 provide/inject 時,需要依附一個元件進行測試。

// test-utils.js
import {createApp} from 'vue';

export function withSetup(composable) {
  let result;

  const app = createApp({
    setup() {
      result = composable();
      // suppress missing template warning
      return () => {};
    },
  });

  app.mount(document.createElement('div'));
  // return the result and the app instance
  // for testing provide / unmount
  return [result, app];
};
// counter.js
import {ref, onMounted} from 'vue';

export function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;
  
  onMounted(() => {
    increment();
  });

  return {
    count,
    increment,
  };
};

result是 composable 的回傳值(return),測試裡面 app.mount();,將執行 onMounted

// counter.test.js
import {withSetup} from './test-utils';
import {useCounter} from './counter.js'

test('useCounter', () => {
  const [result, app] = withSetup(() => useCounter());

  // run assertions
  expect(result.count.value).toBe(0);

  // trigger onMounted hook if needed
  app.mount();

  expect(result.count.value).toBe(1);
});


另外還有一個常犯的錯誤,先看 composable 程式碼,有一個 computed 使用 formatFn 轉換 list:

// useListFormatter.js
import {computed, unref} from 'vue';

export function useListFormatter(list, formatFn) {
  const formattedList = computed(() => (
    unref(list).map(item => formatFn(item))
  ));

  return {
    formattedList,
  };
};

測試時需要注意回傳值被使用之前,formattedList 不會被執行。

// useListFormatter.test.js
import {useListFormatter} from './useListFormatter.js';

test('useListFormatter', () => {
  const list = ['a', 'b'];
  const formatFn = jest.fn();

  formatFn.mockImplementation(value => `new-${value}`)

  const {formattedList} = useListFormatter();
  
  // Don't do it! formatFn won't be excuted until formattedList is called.
  // expect(formatFn).toHaveBeenCalled();
  
  expect(formatFn).not.toHaveBeenCalled();

  expect(formattedList.value).toEqual(['new-a', 'new-b']);
  expect(formatFn).toHaveBeenCalledTimes(2);
  expect(formatFn).toHaveBeenNthCalledWith(1, 'a');
  expect(formatFn).toHaveBeenNthCalledWith(2, 'b');
});


參考資料:

https://vuejs.org/guide/scaling-up/testing.html#testing-composables


2022年3月5日 星期六

測試套件 Jest mock 基礎概念及 spyOn, fn 範例程式

當測試的對象有使用其他引用(import)時,我們希望能做為控制變因,設法聚焦測試的對象。Jest是常用的js單元測試套件,我們會 mock 方法spyOnfn來達成這個目的,Jest 安裝可以參考「[JavaScript] 安裝Jest單元測試」,底下說明幾種常用的情境。

jest.spyOn(object, methodName)

1. [基本用法] 監聽
單純測試某個method被呼叫的次數,或(官方說明),舉例下面範例是輸入兩個數字,並隨機輸出這個範圍內的數字。
// getRandonInt.js

export const getRandonInt = (min, max) => (
    Math.floor(Math.random(max) * (max - min) + min)
);
例如 Math.floor
jest.spyOn(Math, 'floor')
同理 Math.random ,所以可以將測試寫成:
import {getRandonInt} from './getRandonInt.js';

test('Should get random number between input min and max', () => {
    const spyFloor = jest.spyOn(Math, 'floor');
    const spyRandom = jest.spyOn(Math, 'random');

    const result = getRandonInt(1, 100);

    expect(result).toBeGreaterThanOrEqual(1);
    expect(result).toBeLessThanOrEqual(100);

    expect(spyFloor).toHaveBeenCalledTimes(1);

    expect(spyRandom).toHaveBeenCalledTimes(1);
    expect(spyRandom).toHaveBeenCalledWith(100);
});

因此可看到我們監聽的兩個method,第一 toHaveBeenCalledTimes 分別被呼叫的次數,及 toHaveBeenCalledWith 傳入的參數。


2. [進階] 替換回傳值
改變某個method的回傳值,以下面的範例是希望輸入一個值後,可以隨機產生一個數字並得到兩者相乘的結果
// multiplyNumber.js

export const multiplyNumber = num => (
    Math.random(10) * num
);
如果希望控制隨機產生的數字,可以使用 mockImplementation
import {multiplyNumber} from './multiplyNumber.js';

test('Should get the multiple of random number and input num', () => {
    const spyRandom = jest.spyOn(Math, 'random')
        .mockImplementation(() => 5);

    expect(Math.random(10)).toBe(5);
    expect(multiplyNumber(1000)).toBe(5000);

    spyRandom.mockRestore();

    expect(Math.random(10)).not.toBe(5);
});
可以理解成實際我們已經將 Math.random 變成:
Math['random'] = () => 5;

// you could definitely get parameter when method was called
// so implementation would be like ...
// Math['random'] = a => (a + 1);

mockRestore()可以恢復原本method的功能,因此直到我們呼叫 mockRestore()為止,無論我們呼叫幾次 Math.random ,都會按照我們的設定回傳數字 5。


假設希望這個設定是一次性的,則可以改用 mockImplementationOnce,這個寫法比較不容易出錯,是比較推薦的用法。

jest.spyOn(Math, 'random')
    .mockImplementationOnce(() => 5);
    .mockImplementationOnce(() => 20);

expect(Math.random(10)).toBe(5);
expect(Math.random(10)).toBe(20);


jest.fn(implementation)

用法和 spyOn非常類似,可以用來驗證呼叫次數及傳入參數等

const mockFn = jest.fn();

mockFn(100);

expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn).toHaveBeenCalledWith(100);
驗證的部分,toHaveBeenCalledTimestoHaveBeenCalledWith這兩個還有另一個寫法:
expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn.mock.calls.length).toBe(1);

expect(mockFn).toHaveBeenCalledWith(100);
expect(mockFn.mock.calls[0][0]).toBe(100);

calls是一個陣列,長度等同於呼叫的次數,陣列內每一個位置也都是一個陣列,每個位置則對應到呼叫時的參數內容。可以實際印出得到 calls = [[100]],所以calls[0][0]代表的是第一次呼叫時第一個參數是什麼


依照 multiplyNumber.js 的範例,可以使用fn達到同樣的效果,測試結束前也要記得呼叫mockRestore免得影響其他測試‧。

const spyRandom = jest.fn(() => 5);
Math['random'] = spyRandom;
const spyRandom = jest.fn()
    .mockImplementation(() => 5);
Math['random'] = spyRandom;
const spyRandom = jest.fn()
    .mockReturnValueOnce(5);
Math['random'] = spyRandom;


jest.mock(module)

當測試有引入(import)其他模組、函式時,可以使用mock來替換回傳內容,我們稍微改寫剛剛的 multiplyNumber

import {getRandonInt} from './combineArray.js';

export const multiplyNumber = (min, max, num) => (
    getRandonInt(min, max) * num
);

為了清楚此時的getRandonInt已經被替換掉,我們刻意重新命名,在測試裡將回傳值設定為數字 20

import {getRandonInt as mockGetRandonInt} from './getRandonInt';
import {multiplyNumber} from './multiplyNumber';

jest.mock('./getRandonInt');

test('Should get the multiple of random number and input num', () => {
    mockGetRandonInt.mockReturnValueOnce(20);

    expect(multiplyNumber(1, 2, 3)).toBe(60);

    expect(mockGetRandonInt).toHaveBeenCalledTimes(1);
    expect(mockGetRandonInt).toHaveBeenCalledWith(1, 2);
});

另外可以利用requireActual可以取得原始的功能,當我們只需要部份取代時,可以藉此替換部分的內容,其餘皆按照原設定

const {getRandonInt} = jest.requireActual('../src/libs/combineArray');

mockGetRandonInt.mockImplementationOnce((a, b) => a + b);

expect(getRandonInt(1, 2)).toBeLessThanOrEqual(2);

expect(mockGetRandonInt(1, 2)).toBe(3);
expect(mockGetRandonInt).toHaveBeenCalledTimes(1);

最後一個重點,建立和初始化一個class的物件時,可以透過instances來得到建立的物件,它是一個陣列,會依照建立順序放在對應的位置上。

const myMock = jest.fn();

const a = new myMock();

expect(a).toBe(myMock.mock.instances[0]);

參考資料: