4

I am in the process of converting my project from Vue 2 to 3 and also testing library to Vue test utils 2. Before, mocking methods works like magic:

export default {
  methods: {
    greet(text) {
      sayHello('hello world')
    },
    sayHello(text) {
      console.log(text)
    }
  }
}
test('should sample', async () => {
  const spy = jest.spyOn(wrapper.vm, 'sayHello')
  wrapper.vm.greet('hello world')
  expect(spy).toHaveBeenCalledWith('hello world')
})

I tried converting it to composition api:

export default defineComponent({
  setup() {
    function greet(text) {
      sayHello(text)
    }

    function sayHello(text) {
      console.log(text)
    }

    return {
      greet,
      sayHello
    }
  }
})

and now testing is not working at all

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: "hello world"

Number of calls: 0

How do I mock functions that call another functions in Vue 3 + Vue test utils 2?

2 Answers 2

0

you should create your spy functions before the wrapper instance is created (where you use mount or shallowMount). Creating spies before creating instance and using

beforeEach(() => {
  jest.resetAllMocks();
})

in order to reset mocks for following cases should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

0

Read this: https://github.com/vuejs/vue-test-utils/issues/1951#issuecomment-1019091217

lmiller1990 says that we don't possibly modify values ​​inside of the setup.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.