我有一个带有动作的vuex商店 .
//actions.js
import api from '@/api.js'
export default {
getAllProducts ({commit}) {
// call the api and return a promise with the products
api.fetchAllProducts().then((products) => {
commit('getAllProducts', products)
})
}
现在来测试吧!
// actions.spec.js
import actions from './actions.js'
import api from './api.js'
describe('shop actions', () => {
it('calls api and fetches products', () => {
let state = {items: []}
let commit = sinon.spy()
let stub = sinon.stub(api, 'fetchAllProducts')
stub.resolves('a product')
actions.getAllProducts({commit, state})
expect(commit.args).to.deep.equal([
['SET_ALL_PRODUCTS', 'a product']
])
})
})
这是我到目前为止的尝试 . 由于一些原因,它不起作用 .
-
api函数上的sinon存根也不会在actions.js上存根导入的api .
-
api函数返回一个promise,所以测试而不是等待它解析只返回断言,所以commit.args将永远是[]
关于如何测试vuex动作的任何建议 . 我认为主要的困难是存在api模块,我很困惑 . 任何建议表示赞赏:)
1 回答
动作
getAllProducts
应该返回承诺 .那么你的测试代码应该是这样的:
此外,如果您没有从操作中返回promise,我们可以使用async / await .