-
Notifications
You must be signed in to change notification settings - Fork 665
How to unit test inner function(not return) of setup in Vue 2.7/3? #1995
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
Comments
I'm not sure if this helps or not, but I just found that declaring the spy anywhere but the top of the test before the mounting happens is the only way to get it to work accurately. Ex.
Again, I'm not sure if that's what's happening here in your component but thought I'd share in hopes that it helps |
Hey thank you for answering @devtopher! That's an interesting find though problem is I need to pass |
I noticed a similar issue when migrating a component to |
Hummm, indeed, even computed vales are no longer accessible from |
Because that's not how you should be testing components. Do not test component internals. Say you have this: <template>
<div>
<div data-testid="count">Count: {{ count }}</div>
<button data-testid="increment-button" @click="incrementCount">
Increment
</button>
</div>
</template>
<script>
export default {
data: () => ({ count: 0 }),
methods: {
incrementCount() {
this.count++
}
}
}
</script> Most people test it like this: it('calls correct method on button click', () => {
createComponent()
jest.spyOn(wrapper.vm, 'incrementCount').mockImplementation(() => {})
findIncrementButton().trigger('click')
expect(wrapper.vm.incrementCount).toHaveBeenCalled()
expect(wrapper.vm.count).toBe(1)
}) In the code above, it's spying on component methods and making sure that when the button is clicked, the Both of these are wrong. You are testing the framework (Vue itself). You should instead test the component output: const findCount = () => wrapper.find("[data-testid='count']")
const findIncrementButton = () => wrapper.find("[data-testid='increment-button']")
it('increases the count on Increment button click', async () => {
createComponent()
expect(findCount().text()).toBe('Count: 0')
findIncrementButton().trigger('click')
await nextTick()
expect(findCount().text()).toBe('Count: 1')
}) As you can see, we are not touching the component internals. We are only testing the output. Here's a great video about unit testing best practices with Vue. |
@wobsoriano Waouh ! Thanks for the clarification !
Thanks for confirming this feeling I had when looking for Vue test examples. Your example makes more sense to me, and I'll move to this logic then ! |
Subject of the issue
Unable to mock inner function called by a returned function
Steps to reproduce
Expected behaviour
It should have been called
Actual behaviour
The text was updated successfully, but these errors were encountered: