Vuex-module-decorators: How to mock the class properties for unit tests

Created on 18 Dec 2018  路  7Comments  路  Source: championswimmer/vuex-module-decorators

Hi,

I have my module something like this:

export interface IUsersModule {
  users: User[];
}

@Module({
  dynamic: true,
  name: 'users',
  namespaced: true,
  store,
})
class UsersModule extends VuexModule implements IUsersModule {
  users: Users[] = [];
  // ... actions, mutations, etc.
}

export const usersModule = getModule(UsersModule);

And I have my component like this:

<template>
  <div>
    <p v-for="user in users">{{ user.name }}</p>
  </div>
</template>

<script lang="ts">
import { usersModule } from './usersModule';

@Component
export default class MyComponent extends Vue {
  private get users() {
    return usersModule.users;
  }
}
</script>

Now, I want to unit test MyComponent. Is there a way to use jest to mock the users property? I tried to do something like this:

import { usersModule } from './usersModule';

const usersMock = jest.SpyOn(usersModule, 'users');

But, when I do this, I get the error that says:

Cannot spy the users property because it is not a function; object given instead

Can you please give some guidance on this?

Thank you in advance

All 7 comments

I didn't receive any answer, but I did something, and I mention it here in case someone faced the same issue:

What I ended up doing was to use both jest and sinon to do something like this:

jest.mock('./usersModule');
const usersModStub = sinon.stub(usersModule);

Then, whenever I want to mock properties, I do something like this:

usersModStub.users = [ /* ... */ ];

PS: I'm not sure if this is the proper way to do it, but it works for me, so I didn't want to invest more time into it!

So, I'm closing this issue although I expected something from the maintainer :(

Hi @farzadmf, did you ever find an alternative approach?

Hi @spapaseit , It's been a while actually, but I think the thing that I mentioned above was what I ended up with

Thanks @farzadmf. Precisely because it's been a while I thought you might have found a better/different way to do it, even if it was on another project.

Thanks!

I'm receiving this module namespace not found...
And the docs of this lib doesn't even take a simple note about tests. I'm lost in the jungle trying to test things like this:

image

@farzadmf
I solved the problem using the spy method in jest:
const spy = jest.spyOn(<vuexModule> , '<actionName>');

I hope it helps.

I tried with jest.spyOn but I received "XXX property is not declared configurable".

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Hamidrezana picture Hamidrezana  路  4Comments

BonBonSlick picture BonBonSlick  路  5Comments

webcoderkz picture webcoderkz  路  6Comments

davidmoshal picture davidmoshal  路  6Comments

blainehansen picture blainehansen  路  4Comments