Mock inner axios.create()

OK I got it. Here is how I fixed it! I ended up doing without any mocking libraries for axios! Create a mock for axios in src/__mocks__: // src/__mocks__/axios.ts const mockAxios = jest.genMockFromModule(‘axios’) // this is the key to fix the axios.create() undefined error! mockAxios.create = jest.fn(() => mockAxios) export default mockAxios Then in your … Read more

How can I use Jest to spy on a method call?

The key is using jests spyOn method on the object’s prototype. It should be like this: const spy = jest.spyOn(Component.prototype, ‘methodName’); const wrapper = mount(<Component {…props} />); wrapper.instance().methodName(); expect(spy).toHaveBeenCalled(); As found here e.g.: Test if function is called react and enzyme Please note it is also best practice to clear the spied function after each … Read more

How do I set a mock date in Jest?

As of Jest 26 this can be achieved using “modern” fake timers without needing to install any 3rd party modules: https://jestjs.io/blog/2020/05/05/jest-26#new-fake-timers jest .useFakeTimers() .setSystemTime(new Date(‘2020-01-01’)); If you want the fake timers to be active for all tests, you can set timers: ‘modern’ in your configuration: https://jestjs.io/docs/configuration#timers-string EDIT: As of Jest 27 modern fake timers is … Read more

Mocking methods on a Vue instance during TDD

Solution 1: jest.spyOn(Component.methods, ‘METHOD_NAME’) You could use jest.spyOn to mock the component method before mounting: import MyComponent from ‘@/components/MyComponent.vue’ describe(‘MyComponent’, () => { it(‘click does something’, async () => { const mockMethod = jest.spyOn(MyComponent.methods, ‘doSomething’) await shallowMount(MyComponent).find(‘button’).trigger(‘click’) expect(mockMethod).toHaveBeenCalled() }) }) Solution 2: Move methods into separate file that could be mocked The official recommendation is … Read more