Vuex Unit Test:Getter

栏目: 编程语言 · 发布时间: 6年前

内容简介:Vuex 分成 State、Mutation、Getter 與 Action 四部分,由於都是圍繞在 Data,因此都是針對 Data 做測試。本文討論 Getter 的 Unit Test。Vue 2.5.22

Vuex 分成 State、Mutation、Getter 與 Action 四部分,由於都是圍繞在 Data,因此都是針對 Data 做測試。

本文討論 Getter 的 Unit Test。

Version

Vue 2.5.22

Vuex 3.0.1

Vue-test-utils 1.0.0-beta.20

Store

books-info.js

import { fetchBooks } from '@/api/books';

/** mutation */
const setBooks = (state, { books }) => state.books = books;

/** action */
const saveBooks = commit => ({ data }) => commit('setBooks', data);
const loadBooks = ({ commit }) => fetchBooks().then(saveBooks(commit));

/** getter */
const booksCount = ({ books }) => books.length;

export default {
  namespaced: true,
  state: { books: [] },
  mutations: { setBooks },
  getters: { booksCount },
  actions: { loadBooks },
};

一個典型的 Vuex store,包含 statemutationsgettersactions

10 行

/** getter */
const booksCount = ({ books }) => books.length;

booksCount() 為典型的 getter,將 books state 的 length property 傳回。

Unit Test

getter.spec.js

import store from '@/store/modules/books-info';

test('booksCount() getter', () => {
  /** arrange */
  const stub = [1, 2, 3];
  const state = { books: stub };

  /** act */
  const result = store.getters.booksCount(state);

  /** assert */
  expect(result).toBe(3);
});

第 1 行

import store from '@/store/modules/books-info';

將要測試的 store import 進來。

第 3 行

test('booksCount() getter', () => {
  /** arrange */

  /** act */

  /** assert */
});

所有的 unit test 都包在 test() 的第二個參數,以 Arrow Function 表示。

test() 的第一個參數為 description,可描述 test case。

一樣使用 3A 原則寫 unit test。

第 4 行

/** arrange */
const stub = [1, 2, 3];
const state = { books: stub };

要測試 getter,有兩個原則:

books
const stub = [1, 2, 3];

建立要測試的 stub。

const state = { books: stub };

建立 fake state object,並以 stub 建立 state 的初始值。

第 8 行

/** act */
const result = store.getters.booksCount(state);

實際執行 booksCount() getter,變傳入剛在 arrange 建立的 fake state。

bookCount() getter 結果存於 result

11 行

/** assert */
expect(result).toBe(3);

驗證 result 是否等於預期結果。

$ yarn test:unit

Vuex Unit Test:Getter

通過 unit test 得到 綠燈

Conclusion

  • Vuex 的 Getter 本質是 function,且職責很確定,因此 unit test 非常好寫
  • 由於 getter 的職責只有讀取 state,測試手法就是提供 stub 並透過 fake state object 建立 state 初始值,然後執行 getter 並驗證結果是否如預期

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

数据之巅

数据之巅

涂子沛 / 中信出版社 / 2014-5-1 / 65.00元

《数据之巅:大数据革命,历史、现实与未来》从美国建国之基讲起,通过阐述初数时代、内战时代、镀金时代、进步时代、抽样时代、大数据时代的特征,系统梳理了美国数据文化的形成,阐述了其数据治国之道,论述了中国数据文化的薄弱之处,展望了未来数据世界的远景。 “尊重事实,用数据说话”,“推崇知识和理性,用数据创新”,作者不仅意在传承黄仁宇“数目字”管理的薪火,还试图把数据这个科技符号在中国转变为文化符号......一起来看看 《数据之巅》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具