我想测试一个动作,我的动作包含一个api调用
my action in vuex
File contains actions in my store (store 'ex.js')exActions.js
export const exActions = {
getExFromApi({ commit, rootGetters }, { id }) {
getApiExById({ access_token: rootGetters.auth.token, id }).then(res => {
commit('SET_INIT_EX', res)
commit('SET_CURRENT_EX', res)
}).catch(error => {
console.warn(error)
})
},
文件包含调用apiexAPi.js
export const getApiExById= (params, group) => {
// call return promise
}
My File test
// import api
const api = require('../../../src/api/exAPi')
let store = null
describe('Unit Test', function() {
beforeEach(() => {
const localVue = createLocalVue()
localVue.use(Vuex)
store = new Vuex.Store({
modules: {
exStore
}
})
})
context('test : action -> getExFromApi', function() {
it('1', async function() {
let rootGetters = {
auth: {
token: 'aaa'
}
}
let commit = cy.spy()
// mock call api , return a promise defined
cy.stub(api, 'getApiExById').resolved('foo')
// start the method
await store.dispatch('getExFromApi', ({commit, rootGetters}, {id: '1'}))
// expect 'foo' value because cy.stub api return 'foo'
expect(commit.args).to.deep.equal([
['SET_INIT_EX', 'foo'],
['SET_CURRENT_EX', 'foo']
])
cy.stub.restore()
start file with node ->/node_modules/。bin/柏树open-ct问题是,'getExFromApi'启动,但启动真正的调用api,而不是模拟。
我做错了什么?谢谢你的帮助。
当你将api导入测试时,它与应用程序正在使用的实例不同。
const api = require('../../../src/api/exAPi') // creates a new instance
要获得相同的实例,在storeex.js中import * as api from '../api/exAPi' // import module
const {getApiExById} = api // method for use in exActions
if (window.Cypress) { // are we testing?
window.api = api // allow test to see module instance
}
在测试
cy.window().then(win => {
// mock call api , return a promise defined
cy.stub(win.api, 'getApiExById').resolved('foo') // mocking the same instance
}
我对cy.window().then(
有点警惕,也许这个更好
// mock call api , return a promise defined
const win = cy.state('window');
cy.stub(win.api, 'getApiExById').resolved('foo') // mocking the same instance
在ex.js中导入模块
因为你在exApi.js
中使用命名导出,但存根失败,我假设没有默认导出,即模块是而不是导出如下
...
export default {
getApiExById
}
如果是,将ex.js
中的默认导入更改为
import * as api from '../api/exAPi' // import module
...
Ref如何导出ES6中的存根功能?