Test the data validation

The reason we need to test the data validation is to make sure there is validation in place and user input has been properly validated before being sent to the backend. Let's add the following test to RegisterPage.spec.js to verify that, when the value of the email address is invalid, the registrationService.register() method won't be invoked:

...
import Vuelidate from 'vuelidate'
import registrationService from '@/services/registration'
...
localVue.use(Vuelidate)
...
// Mock dependency registratioService
jest.mock('@/services/registration')

describe('RegisterPage.vue', () => {
...
it('should fail when the email address is invalid', () => {
const spy = jest.spyOn(registrationService, 'register')
wrapper.vm.form.emailAddress = 'bad-email-address'
wrapper.vm.submitForm()
expect(spy).not.toHaveBeenCalled()
spy.mockReset()
spy.mockRestore()
})
})

As you can see, we import Vuelidate and then apply it to localVue. We also import registrationService. Even though importing registrationService is placed above jest.mock('@/services/registration'),  the jest.mock() method will still be executed before the import, because Jest will automatically hoist jest.mock() calls to the very top of the module, before any imports. In this way, the imported registrationService is actually the mock we created earlier, inside the __mock__ folder.

Inside the test method, we use jest.spyOn() to create a spy of the register() method. This spy is also a mock function. As a spy, it has the ability to track calls to the method. As you can see, we use expect(spy).not.toHaveBeenCalled() to verify that the register() method isn't invoked. At the end of the test, we use mockReset() to clear all of the calls stored in the mock and then use mockRestore() to restore the original behavior of the register() method.

Now, if you run the unit test with the npm run test:unit command, you should see that the test failed, which is expected. Let's implement the validation to make the test pass.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.194.123