unit-testing - 在 vuex 操作中模拟 api 调用
问题描述
我有一个带有动作的 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 模块进行存根,而且我很困惑。任何建议表示赞赏:)
解决方案
该操作getAllProducts
应返回承诺。
getAllProducts ({ commit }) {
return api.fetchAllProducts().then((products) => {
commit('SET_ALL_PRODUCTS', products)
})
}
那么你的测试代码应该是这样的:
describe('shop actions', () => {
it('calls api and fetches products', done => {
let state = {items: []}
let commit = sinon.spy()
let stub = sinon.stub(api, 'fetchAllProducts')
stub.resolves('a product')
actions.getAllProducts({commit, state}).then(() => {
expect(commit.args).to.deep.equal([
['SET_ALL_PRODUCTS', 'a product']
])
done()
})
stub.restore()
})
})
此外,如果您没有从操作中返回承诺,我们可以使用 async/await。
it('calls api and fetches products', async () => {
let state = {items: []}
let commit = sinon.spy()
let stub = sinon.stub(api, 'fetchAllProducts')
stub.resolves('a product')
await actions.getAllProducts({commit, state})
expect(commit.args).to.deep.equal([
['SET_ALL_PRODUCTS', 'a product']
])
stub.restore()
})
推荐阅读
- php - Bootstrap / SQL:将多个选定的数据更新到 SQL 数据库
- postgresql - postgresql 11 选择查询时间去增加
- css - 无覆盖的 React 组件渲染
- reactjs - ReferenceError:刷新nextjs页面时未定义文档
- java - Android 和 Amazon EC2 互连问题
- laravel - 使用 Laravel carbon 计算接下来的 X 天没有星期天
- eclipse - Eclipse - 相同版本,但在不同安装中的“EMF Common”插件版本不同
- firefox - Firefox 无法在 wss 建立与服务器的连接
- pandas - Pandas,删除重复行,保留字符串长度最短的行
- javascript - 定义元素样式时禁用 .droppable() 吗?