Trying to unit test the functions inside an exported module with the help of Jest
The module is the following:
export default {
errorNotification (title, text) {
Vue.notify({
group: 'max-fordham',
type: 'error',
title: title,
text: text
})
},
infoNotification (title, text) {
Vue.notify({
group: 'max-fordham',
type: 'info',
title: title,
text: text
})
},
successNotification (title, text) {
Vue.notify({
group: 'max-fordham',
type: 'success',
title: title,
text: text
})
},
warningNotification (title, text) {
Vue.notify({
group: 'max-fordham',
type: 'warning',
title: title,
text: text
})
}
}
The test I'm trying to write is:
import notifications from '@/services/notifications.service'
describe('Notifications tests', () => {
test('successNotification should set title to title and text to text ', () => {
let title = 'test'
let text = 'test'
//let successNotification = jest.fn()
notifications.successNotification(title, text)
expect(title).toEqual('test')
expect(text).toEqual('test')
})
})
When I run this I receive the following error:
TypeError: _vue.default.notify is not a function
Now, as far as I understand, the error is due to me not mocking _vue.default.notify
, however, I am not sure how to actually do that. Some help will be appreciated.
You can mock Vue
module manually using jest.mock(moduleName)
.
For example:
index.ts
:
import Vue from './Vue';
export default {
errorNotification(title, text) {
Vue.notify({
group: 'max-fordham',
type: 'error',
title: title,
text: text
});
},
infoNotification(title, text) {
Vue.notify({
group: 'max-fordham',
type: 'info',
title: title,
text: text
});
},
successNotification(title, text) {
Vue.notify({
group: 'max-fordham',
type: 'success',
title: title,
text: text
});
},
warningNotification(title, text) {
Vue.notify({
group: 'max-fordham',
type: 'warning',
title: title,
text: text
});
}
};
Vue.ts
: I create the Vue
module to simulate the real Vue
module.
export default {
notify(payload) {
//
}
};
index.spec.ts
:
import notifications from './';
import Vue from './Vue';
jest.mock('./Vue.ts');
describe('Notifications tests', () => {
test('successNotification should set title to title and text to text ', () => {
Vue.notify = jest.fn().mockReturnValueOnce({});
const title = 'test';
const text = 'test';
notifications.successNotification(title, text);
expect(Vue.notify).toBeCalledWith({
group: 'max-fordham',
type: 'success',
title,
text
});
});
});
Unit test result:
PASS src/stackoverflow/58239972/index.spec.ts
Notifications tests
✓ successNotification should set title to title and text to text (12ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.773s
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.