Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Want to mock/stub component method in created/mounted lifecycle. #790

Closed
MushengLiaoDavis opened this issue Jul 23, 2021 · 2 comments
Closed

Comments

@MushengLiaoDavis
Copy link

MushengLiaoDavis commented Jul 23, 2021

Hi,

Sometimes, I really need to mock/stub the component method in created/mounted lifecycle.(like callA method). Have any idea to handle this situation ?

wrapper = shallowMount(MyComponent, { global: { }, methods: { callA: sinon.stub() // <- Mock method } });

@cexbrayat
Copy link
Member

Hi @MushengLiaoDavis

You can read the comments in this thread to give you an idea on how we usually do it: #775 (comment)

Feel free to reopen if that's not what you're looking for, but that should help!

@MushengLiaoDavis
Copy link
Author

In vue-test-utils v1.x, we can mock(stub) component methods for the created/mouted lifecycle as follows:

SFC (class-style component)

// ignore other code ...
created() {
}

mounted() {
     this.callThirdPartyLib();
}

callThirdPartyLib() {
    // call third-party libaray
}

In test file

// use sinon, chai tool

wrapper = shallowMount(MyComponent, {
      methods: {     // In vue-test-utils 2.x  doesn't support mocking methods while mounting component
        callThirdPartyLib: sinon.stub(),     // Don't want to call this real method, so stub it.
        disableTab: sinon.stub(),
        pageScrollTop: sinon.stub()
      },
      localVue,
      store,
});

it('...', () => {
    expect(wrapper.vm.callThirdPartyLib).to.have.been.calledOnce;
})

vue-test-utils v2.x
I know we can stub the http request action (axios) in created/mounted lifecycle. This behavior is independent (gloabl function or gloabl instance) from component, so they are easy to stub. But in my scenario, just don't want to call real method (callThirdPartyLib) while mounting component.

import axios from 'axios';

sinon.stub(axios, 'get').resolves({
  data: {
            // some data here
        }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants