Vuex Unit Test:Getter

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

内容简介: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 並驗證結果是否如預期

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

查看所有标签

猜你喜欢:

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

自制搜索引擎

自制搜索引擎

[日]山田浩之、[日]末永匡 / 胡屹 / 人民邮电出版社 / 2016-1 / 39.00元

《自制搜索引擎》聚焦于Google和Yahoo!等Web搜索服务幕后的搜索引擎系统,首先讲解了搜索引擎的基础知识和原理,接着以现实中的开源搜索引擎Senna/Groonga为示例,使用该引擎的源代码引导读者亲自体验搜索引擎的开发过程。这部分讲解涉及了倒排索引的制作和压缩、检索的处理流程以及搜索引擎的优化等内容。又简单介绍了一些更加专业的搜索引擎的知识和要点,为读者今后进一步学习打下了基础。本书适合......一起来看看 《自制搜索引擎》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具