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 並驗證結果是否如預期

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

查看所有标签

猜你喜欢:

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

Computers and Intractability

Computers and Intractability

M R Garey、D S Johnson / W. H. Freeman / 1979-4-26 / GBP 53.99

This book's introduction features a humorous story of a man with a line of people behind him, who explains to his boss, "I can't find an efficient algorithm, but neither can all these famous people." ......一起来看看 《Computers and Intractability》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

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

UNIX 时间戳转换