You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuex Action测试遇报错:mockImplementationOnce非函数及拦截器问题

Vuex Action测试问题排查

我是Vue测试新手,跟着Edd Yerburgh的*《Testing Vue.js Applications》*一书完成了Vuex getter和mutation的测试,但测试action时遇到了问题。

Store结构

store folder
  - mutations.js
  - actions.js
  - getters.js

Login Action代码

async login( { commit, dispatch }, payload ) {
    try {
      const username = payload.user
      const passwordHash = payload.password
      const hashFunction = payload.hashFunction
      if (!username || !passwordHash || !hashFunction) throw Error

      await axios.post(
        `${API_URL}/${AppEndpoints.login}`,
        {
          user: username,
          password: passwordHash,
          hashFunction: hashFunction,
        },
        {
          headers: {
            "Content-Type": "application/json"
          }
        }
      )
      .then( function( response ) {
        if (response.data && response.data.data && response.data.success && !response.data.error) {
          commit(MUTATION.SET_USER_NAME, username)
          commit(MUTATION.SET_USER_PASSWORD, passwordHash)
          commit(MUTATION.SET_USER_HASH_FUNCTION, hashFunction)
        } else {
          return Promise.reject(Error(response?.data?.errorMsg || response?.data || "Error: authentication failed"))
        }
      })
      .catch(function(error) {
        return Promise.reject(Error(error.response?.data?.errorMsg || error.response?.data || error.message || "Error: authentication failed"))
      } );
    } catch (error) {
      dispatch('clearUserAndPassword')
      commit(MUTATION.SET_ERROR_MESSAGE, error.message)
    }
  }

初始测试代码及报错

我编写的测试代码:

it( 'should dispatch login action with full payload', async function () {
    const payload = {
      user: "test",
      password: "test",
      hashFunction: "sha256"
    };
    actions.login.mockImplementationOnce( () => {
      return Promise.resolve();
    } );

    const commit = jest.fn();
    await actions.login( { commit }, payload );
    await flushPromises();
    expect( commit ).toHaveBeenCalledWith( MUTATION.SET_USER_NAME, payload.user );
  } );

运行测试后出现错误:

_actions.default.login.mockImplementationOnce is not a function
TypeError: _actions.default.login.mockImplementationOnce is not a function

编辑1:修改后的测试代码及新错误

按照建议调整测试代码后,出现新的错误。修改后的测试代码如下:

import axios from "axios";
import flushPromises from 'flush-promises'
import actions from "@/store/actions";
import * as MUTATION from "@/store/mutation-types";

let url = '';
let body = {};

jest.mock( "axios", () => ( {
  post: jest.fn( ( _url, _body ) => {
    return new Promise( ( resolve ) => {
      url = _url
      body = _body
      resolve( true )
    } )
  } )
} ) );

describe( 'Store actions', () => {
  it( 'should dispatch login action with full payload', async function () {
    const response = {
      data: []
    };
    axios.post.mockResolvedValue( response );

    const payload = {
      user: "test",
      password: "test",
      hashFunction: "sha256"
    };
    const commit = jest.fn();
    await actions.login( { commit }, payload );

    await flushPromises();

    expect( axios.post ).toHaveBeenCalledTimes( 1 );
    expect( commit ).toHaveBeenCalledWith( MUTATION.SET_USER_NAME, payload.user );
  } );
} )

现在的错误提示:

TypeError: Cannot read properties of undefined (reading 'request')

该错误来自store index中的这段代码:

export const requestInterceptor = config => {
  config.signal = abortingControllers?.route?.signal
  config.withCredentials = true
  return config
}
axios.interceptors.request.use(requestInterceptor)

请问这种情况该如何处理?是否需要同时mock这个拦截器?


内容的提问来源于stack exchange,提问作者Dairelys García Rivas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:46:47