Vue unit testing - mocking imported services when

2019-08-14 11:07发布

问题:

I'm playing with mount() from vue-test-utils, have a component that imports services that should be mocked in the unit test.

I see that mount() has a mocks option, but trying to extrapolate the example given at guides, common-tips, mocking injections to the scenario of an injected service is eluding me.

mount(Component, {
  mocks: {
    ...?
  }
})

The component simply imports the service, which is plain JS

import DataService from '../services/data.service'

I can get it working using the inject-loader which is detailed here Testing With Mocks

The code that does work

const MyComponentInjector = require('!!vue-loader?inject!./MyComponent.vue')
const mockedServices = {
  '../services/data.service': {
    checkAll: () => { return Promise.resolve() }
  },
}
const MyComponentWithMocks = MyComponentInjector(mockedServices)

const wrapper = mount(MyComponentWithMocks, { store: mockStore, router })

What is the syntax for mount(MyComponent, { mocks: ... })?

Since mount() has a mocks option, should it not be possible to pass mockedServices to it in some form?

回答1:

mocks refers to the Vue instance. You're trying to mock a file dependency, which is a different problem. As you said, one solution is inject-loader. Another is the babel-plugin-rewire.

Let me clear up what the mocks option does.

mocks adds properties to the Vue instance.

If you have an app that injects $route, you might have a component that tries to access it: this.$route.path:

...
  methods: {
    logPath() {
      console.log(this.$route.path)
    }
  } 
... 

If you try to mount this component without installing Vue router, it will throw an error. To solve this, you can use the mocks mount option to inject a mock $route object to the Vue instance:

const $route = { path: 'some/mock/value' }
mount(Component, {
  mocks: {
    $route
  }
})