chai-redux-mock-store报错:ReferenceError: createMockStore未定义求助
Hey there, let's troubleshoot that ReferenceError: createMockStore is not defined error you're hitting when running npm run test with chai-redux-mock-store. Here are the most common fixes to check step by step:
1. Double-check your dependencies are installed correctly
First, chai-redux-mock-store is a chai assertion plugin that relies on redux-mock-store under the hood. Make sure both packages are installed as dev dependencies:
npm install --save-dev chai-redux-mock-store redux-mock-store
You can verify they're installed by running:
npm list chai-redux-mock-store redux-mock-store
If either is missing, the install command above will fix that.
2. Fix your test/test_helper.js setup
Most projects use a test helper to globalize chai plugins and mock store utilities. Here's the correct way to set it up:
import chai from 'chai'; import chaiReduxMockStore from 'chai-redux-mock-store'; import configureMockStore from 'redux-mock-store'; // This comes from redux-mock-store, not chai-redux-mock-store! // Mount the chai assertion plugin chai.use(chaiReduxMockStore); // Create and expose the mock store creator globally const middlewares = []; // Add your app's middlewares here (e.g., redux-thunk) global.createMockStore = configureMockStore(middlewares);
A common mistake here is confusing chai-redux-mock-store (which adds chai assertions) with redux-mock-store (which provides the configureMockStore function to create your mock store instance).
3. Verify your test file is accessing createMockStore correctly
If you aren't using a global test helper, you'll need to import and initialize the mock store directly in Login_spec.jsx:
import chai from 'chai'; import chaiReduxMockStore from 'chai-redux-mock-store'; import configureMockStore from 'redux-mock-store'; // Set up the plugin chai.use(chaiReduxMockStore); // Initialize your mock store creator const createMockStore = configureMockStore([]); // Add your middlewares here // Now you can use createMockStore in your tests describe('Login Component', () => { it('dispatches login action', () => { const store = createMockStore({}); // ... rest of your test logic }); });
Also, double-check for typos—make sure you're writing createMockStore (camelCase) consistently, not a misspelled version like CreateMockStore.
4. Ensure test_helper.js is loaded in your test environment
If your test helper is set up correctly but still not working, confirm it's being loaded before your tests run:
- For Mocha: Update your
package.jsontest script to require the helper:{ "scripts": { "test": "mocha --require test/test_helper.js test/**/*.spec.jsx" } } - For Jest: Add the helper to your
jest.config.js(orpackage.jsonjest settings):module.exports = { setupFilesAfterEnv: ['<rootDir>/test/test_helper.js'] };
内容的提问来源于stack exchange,提问作者neridaj

