内容简介: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,包含 state 、 mutations 、 getters 與 actions 。
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
通過 unit test 得到 綠燈 。
Conclusion
- Vuex 的 Getter 本質是 function,且職責很確定,因此 unit test 非常好寫
- 由於 getter 的職責只有讀取 state,測試手法就是提供 stub 並透過 fake state object 建立 state 初始值,然後執行 getter 並驗證結果是否如預期
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Beautiful Code
Greg Wilson、Andy Oram / O'Reilly Media / 2007-7-6 / GBP 35.99
In this unique work, leading computer scientists discuss how they found unusual, carefully designed solutions to difficult problems. This book lets the reader look over the shoulder of major coding an......一起来看看 《Beautiful Code》 这本书的介绍吧!