reactjs 类型错误:createSlice不是来自vitest的函数

pftdvrlh  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(152)

我正在构建一个井字游戏在react与redux,并试图使用vitest测试。我已经设置板切片和存储,但当试图运行我的第一个测试,我得到下面的错误

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/slices/board/reducers/updateMoveReducer.test.js [ src/slices/board/reducers/updateMoveReducer.test.js ]
TypeError: createSlice is not a function
 ❯ src/slices/board/board.js:11:20
      9| };
     10| 
     11| const boardSlice = createSlice({
       |                    ^
     12|  name: 'board',
     13|  initialState,
 ❯ src/slices/board/reducers/updateMoveReducer.test.js:1:31

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯

 Test Files  1 failed (1)
      Tests  no tests
   Start at  13:36:13
   Duration  1.27s (transform 371ms, setup 0ms, collect 0ms, tests 0ms)

这是我的gameStore代码

import boardReducer from './slices/board/board';
import { configureStore } from '@reduxjs/toolkit';

export const gameStore = configureStore({
    reducer: {
        board: boardReducer,
    },
});

这是电路板切片

import { createSlice } from '@reduxjs/toolkit';
import { updateMoveReducer } from './reducers/updateMoveReducer';
const initialState = {
    tiles: [
        [undefined, undefined, undefined],
        [undefined, undefined, undefined],
        [undefined, undefined, undefined],
    ],
};

const boardSlice = createSlice({
    name: 'board',
    initialState,
    reducers: {
        updateMove: updateMoveReducer,
    },
});

export const { updateMove } = boardSlice.actions;
export default boardSlice.reducer;

这是当前的updateMoveReducer。

export const updateMoveReducer = (state, action) => {
    return state;
};

我在应用程序中使用Provider设置了商店,可以看到在使用Redux Chrome开发工具时切片设置正确。
redux chrome dev tool screenshot
尝试运行以下测试,但出现错误。

import { updateMove } from '../board';
import { gameStore } from '../../../gameState';
import { expect, it, describe } from 'vitest';

describe('updateMoveReducer', () => {
    it('should update the tiles array with the move', () => {
        const player = 'x';
        const move = { x: 0, y: 0 };
        gameStore.dispatch(updateMove({ player, move }));
        const state = gameStore.getState().board;
        expect(state.tiles[move.x][move.y]).toBe(player);
    });
});
tmb3ates

tmb3ates1#

请参阅本期https://github.com/vitest-dev/vitest/issues/2509,其中提到了vitest最新版本中的默认导出问题。
对我来说,降级到0.23.4目前是可行的,尽管我不确定这个问题是在哪里引入的。
你可以通过在测试中使用console.log(createSlice)来追踪它,发现它是未定义的,但是如果你依次使用import * as things from '@reduxjs/toolkitconsole.log(things),它肯定是定义的,在{ default: .... }中,所以在vitest上下文中它在things.default.createSlice中,但是它应该在things.createSlice中。

相关问题