Mocking method on component (using Jest)
See original GitHub issueHi,
I am trying out avoriaz with Jest. So far this library is great, thanks a lot.
I want to mock a method that makes an api request.
My code looks something like
SomeComponent.vue
<template>
<form>
<button type="button" id="my-button" @click="save">Btn</button>
</form>
</template>
<script>
export default {
methods: {
save () {
// stuff
}
}
}
</script>
Test
import { shallow } from 'avoriaz'
import Vue from 'vue'
import SomeComponent from './SomeComponent.vue
describe('mocks a method', () => {
it('mocks it', () => {
const wrapper = shallow(SomeComponent)
// I want to mock the `save` method with `jest.fn()` - how do I do that?
/* I have tried...
wrapper.methods().save == jest.fn()
wrapper.vm.save = jest.fn()
*/
// rest of the test
wrapper.find('#my-button')[0].trigger('click')
expect(/* mock to have been called */)
}
}
I saw some examples around using sinon, but the same should work for jest. So I would like to know how I can mock a function - I was struggling to find an example. I did see one other example where a mocked function was passed using propsData
? Is that what I should be doing?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:18 (13 by maintainers)
Top Results From Across the Web
How to mock React component methods with jest and ...
The method can be mocked in this way: it('handleNameInput', () => { let wrapper = shallow(<MyComponent/>); wrapper.instance().
Read more >How To Mock A React Component In Jest - Chak Shun Yu
To mock a React component, the most straightforward approach is to use the jest.mock function. You mock the file that exports the component...
Read more >Mock Functions
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function...
Read more >How to mock a function in Jest for a React and Typescript app
Jest has a spyOn function, which can resolve the problem and make the test much better. jest.spyOn allows a method in an object...
Read more >Mocking React Components with Jest
First, to mock a component you use jest.mock("path/to/RealComponent") . You can specify an mock implementation inline like jest.mock("../src ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You were nearly there:
I’m going to add a setMethod method at some point to make this easier to understand.
setMethods
has been merged and is now live in v3.4.0 👏