feathersjs-ecosystem / feathers-vuex

Integration of FeathersJS, Vue, and Nuxt for the artisan developer
https://vuex.feathersjs.com
MIT License
445 stars 110 forks source link

Testing feathers-vuex using Jest #515

Open juliolugo96 opened 3 years ago

juliolugo96 commented 3 years ago

First of all, Feathers is a charm. This is the first real issue I'm facing since I started working with it. Me and my friends have a massive respect for you, mr. @daffl, greetings from ULA - Venezuela.

Steps to reproduce

I'm trying to run Jest tests suite using yarn run test in a project that is using feathers-vuex using the code I left below.

Expected behavior

Test suite runs correctly.

Actual behavior

The problem goes with this line:

 FAIL  test/Authentication.spec.js (6.029s)
  ● Console

    console.error node_modules/vue/dist/vue.common.dev.js:630
      [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'query' of undefined"

      found in     

      ---> <Anonymous>
             <Root>

  ● user authentication process › authentication page renders correctly

    /home/user/project/node_modules/feathers-vuex/dist/index.js:6
    import FeathersVuexFind from './FeathersVuexFind'
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

       7 | import { CookieStorage } from 'cookie-storage'
       8 | import { iff, discard } from 'feathers-hooks-common'
    >  9 | import feathersVuex, { initAuth, hydrateApi } from 'feathers-vuex'
         | ^
      10 | // Get the api url from the environment variable
      11 | const apiUrl = process.env.API_URL
      12 | let socket

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (plugins/feathers.js:9:1)
      at Object.<anonymous> (store/index.js:1:1)

Particularly, I've this call in one of my inner components in VueJS, which seems to be failing:

 methods: {
    evalQuery() {
      const { error } = this.$route.query

I might think that this problem could be solved including Vuex and NuxtStore inside my test suite. However, the problem keeps showing up. I also tried to transpile that specific module with Babel, but the problem stands still. I don't know what to do at this point, honestly. I would appreciate your help.


### System configuration

My `jest.config.js` looks like this:

```js
module.exports = {
  globalSetup: "<rootDir>/jest.setup.js", // this line is the only change here
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js'
  },
  moduleFileExtensions: ['js', 'vue', 'json'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/components/**/*.vue',
    '<rootDir>/pages/**/*.vue'
  ]
}

My jest.setup.js:

import { Nuxt, Builder } from "nuxt"
import nuxtConfig from "./nuxt.config"

// these boolean switches turn off the build for all but the store
const resetConfig = {
  loading: false,
  loadingIndicator: false,
  fetch: {
    client: false,
    server: false
  },
  features: {
    store: true,
    layouts: false,
    meta: false,
    middleware: false,
    transitions: false,
    deprecations: false,
    validate: false,
    asyncData: false,
    fetch: false,
    clientOnline: false,
    clientPrefetch: false,
    clientUseUrl: false,
    componentAliases: false,
    componentClientOnly: false
  },
  build: {
    indicator: false,
    terser: false
  }
}

// we take our nuxt config, lay the resets on top of it,
// and lastly we apply the non-boolean overrides
const config = Object.assign({}, nuxtConfig, resetConfig, {
  srcDir: nuxtConfig.srcDir,
  ignore: ["**/components/**/*", "**/layouts/**/*", "**/pages/**/*"]
})

const buildNuxt = async () => {
  const nuxt = new Nuxt(config)
  await new Builder(nuxt).build()
  return nuxt
}

module.exports = async () => {
  const nuxt = await buildNuxt()

  // we surface this path as an env var now 
  // so we can import the store dynamically later on
  process.env.buildDir = nuxt.options.buildDir
}

My test file looks like this:

import { shallowMount, createLocalVue } from '@vue/test-utils';
import Sign from '@/pages/sign.vue';
import GSignIn from '@/components/SignIn'; 
import GSignUp from'@/components/SignUp'; 
import Buefy from 'buefy';
import Vuex from 'vuex';

const localVue = createLocalVue();
localVue.use(Buefy);
localVue.use(Vuex);

describe('user authentication process', () => {

  let NuxtStore;
  let store;

  beforeAll(async () => {
    // note the store will mutate across tests
    const storePath = `${process.env.buildDir}/store`
    NuxtStore = await import(storePath);

    console.log("Whats here: ", NuxtStore)
  })

  beforeEach(async () => {
    store = await NuxtStore.createStore()
  })

  test("authentication page renders correctly", () => {
    const wrapper = shallowMount(Sign, {localVue});

    const signIn = wrapper.findComponent(GSignIn);

    expect(signIn.exists()).toBe(true);

    const signUp = wrapper.findComponent(GSignUp);
    expect(signUp.exists()).toBe(true);
  });

})

Module versions (especially the part that's not working): feathers-vuex 3.10.4

NodeJS version:

v12.16.1

Operating System:

Linux Mint 18.2 64-bit

Browser Version:

Google Chrome Version 84.0.4147.105 (Official Build) (64-bit)

React Native Version: N/A Module Loader: N/A

marshallswain commented 3 years ago

Hmm. I have very little experience with Jest since I use Mocha for everything. I've tried to switch to Jest once a year since it came out, but I find myself much more productive with Mocha. Anyway, as a result of this I won't be much help. However, if you can comment with a link to a repo that demonstrates this exact problem, you're more likely to find one of the community members who might be able to troubleshoot. If you choose to do this, please keep the repo as simple as you possibly can so it's easier to isolate the problem. Thanks!

azable commented 3 years ago

I had the same issue. I was able to fix it by adding an exclusion for feathers-vuex via transformIgnorePatterns in jest.config.js - see https://cli.vuejs.org/config/#transpiledependencies for details.

module.exports = {
  ....
  transformIgnorePatterns: ['/node_modules/(?!vue-awesome|feathers-vuex)']
};

Of course in your specific case you would omit vue-awesome as you aren't using it. This might be worth mentioning in https://vuex.feathersjs.com/getting-started.html#project-configuration to accompany the various transpilation scenarios.

marshallswain commented 3 years ago

Thanks, @alzab. This definitely needs to go into the docs