Currently, I am working on creating a login component with vue, vuex, and vuetify. To implement this, I opted for using a namespaced auth module in the store; however, I encountered an issue along the way.
I have adopted a Test-Driven Development (TDD) approach for this project. While my end-to-end test is successful, I ran into a problem with a unit test that uses a mockStore to verify the dispatch of a specific action only:
describe('Login component', () => {
let wrapper
const mockStore = {
dispatch: jest.fn(),
}
beforeEach(() => {
wrapper = mount(Login, {
localVue,
mocks: { $store: mockStore },
computed: {
error: () => 'test error',
},
data: () => ({
valid: true
})
})
})
it('should dispatch login action', async () => {
// Test implementation goes here...
})
})
The login component utilizes mapActions
as shown below:
...mapActions('auth', [LOGIN])
Triggering the action through a button click looks like this:
<v-btn
color="info"
@click="login({ username, password })"
data-test="login"
:disabled="!valid"
>Login</v-btn>
However, I encountered an error message stating:
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'auth/' of undefined"
If I remove the namespace from mapActions
, the dispatched action name does not include the namespace, leading to test failures:
- Expected
+ Received
- "auth/login",
+ "login",
After some trial and error, I managed to resolve the issue by mapping actions in a slightly different manner:
...mapActions({ login: `auth/${LOGIN}` })
Despite finding a solution, I prefer using the namespaced version due to potential complexities when dealing with multiple actions in the future.
I delved into the Vuex source code briefly but found it challenging when attempting to access _modulesNamespaceMap
. At this point, I am considering whether to abandon mocking and utilize a real store for testing purposes.
If you would like to explore the full project, please visit this link and refer to commit 4a7e749d4
for relevant details.