尝试在 Jest
的帮助下对导出模块内的函数进行单元测试
该模块如下:
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
})
}
}
我想要编写的测试是:
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')
})
})
当我运行此程序时,我收到以下错误:
TypeError: _vue.default.notify is not a function
现在,据我了解,错误是由于我没有 mock _vue.default.notify
,但是,我不确定如何实际做到这一点。一些帮助将不胜感激。
最佳答案
您可以使用 jest.mock(moduleName)
手动模拟 Vue
模块。
例如:
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
:我创建了 Vue
模块来模拟真实的 Vue
模块。
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
});
});
});
单元测试结果:
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
关于javascript - 单元测试导出的模块功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239972/