While testing a login request, I encountered an issue where jest did not call the mock:
This is my test :
const User = '123123'
jest.mock('axios', () => ({
get: jest.fn(),
post: (_url, _body) => new Promise((resolve, reject) => {
if (_body.username != User) return reject({ data: { auth: false } })
resolve({
data: {
auth: true,
data: '123456789789213',
name: 'Indra'
}
})
})
}))
describe('Component', () => {
let actions
let store
beforeEach(() => {
actions = {
logIn: jest.fn()
}
store = new Vuex.Store({
actions
})
})
test('Logins in server', () => {
const wrapper = shallowMount(Login, { store, localVue })
const inputLogin = wrapper.find('[name=login]')
const inputPassword = wrapper.find('[name=password]')
//fake user and password
inputLogin.element.value = User
inputPassword.element.value = 'Indra1234'
wrapper.find('button').trigger('click')
expect(actions.logIn).toHaveBeenCalled()
})
})
And here is the login function:
methods : {
AuthUser () {
if(this.server == "Select a server") return this.$swal('Attention', 'Please select a server!', 'error');
console.log("Requesting login")
this.loading = true
try {
axios.post(this.server+"/auth",
{
username: this.id,
password: this.password
})
.then(result => {
console.log(result)
if(result.data.auth) {
this.tk = result.data.data
this.nome = result.data.name
this.logIn
setTimeout(() => {
console.log("Hi")
$("body, this").css("background-color","#FBF5F3");
// this.$router.push('/home')
this.$eventHub.$emit('logIn', 1);
}, 1000);
} else {
this.loading = false
this.$swal('Attention', 'Incorrect username or password!', 'warning');
}
}).catch((er) => {
this.loading = false
this.$swal('Sorry', 'A communication error with the server occurred!', 'error');
console.log(er)
})
} catch (error) {
this.loading = false
this.$swal('Sorry', 'An error occurred while logging in', 'error');
console.log('Internal Error: ', error)
}
}
}
When running the test, it can be seen that the console log "Requesting login" is being called. The test configurations were set up using Vue CLI 3 and I referred to for guidance.