javascript - Mixpanel 模拟不断返回为未定义
问题描述
我有一个非常基本的静态应用程序,它具有根据用户在 UI 中单击的元素重定向用户的业务逻辑。我添加了 Mixpanel,并在用户被重定向之前跟踪事件。我正在尝试使用 Jest 测试框架创建测试,但是在模拟 mixpanel 上的跟踪方法调用时遇到了困难。
问题的症结在于我无法在运行测试时模拟 mixpanel。我已经阅读了 Jest 文档并在社区中搜索了答案,但是每次我运行测试时,它都会失败并显示TypeError: Cannot read property 'track' of undefined。如果这是显而易见的事情,你将不得不原谅我,JavaScript 不是我的本地编程语言,所以当需要构建测试时,我对它生疏了。:)
索引.html
<!doctype html>
<html class="no-js" lang="">
<head>
<!-- start Mixpanel -->
<script type="text/javascript">...Mixpanel script</script>
<script src="js/scripts.js"></script>
<script type="text/javascript">
const { sources } = window.parseSourcesFromURL(window.location.href)
const sourceObj = window.convertToObj(sources)
mixpanel.track("Page View", sourceObj)
</script>
<!-- end Mixpanel -->
</head>
<body>
<div>
<div class="age-links">
<button onClick=redirectFunc(true)>YES</button>
<button onClick=redirectFunc(false)>NO</button>
</div>
</div>
</body>
</html>
js/scripts.js
(function() {
const convertToObj = () => ...
const getTrackingData = () => ...
const parseSourcesFromURL = () => ...
const redirectFunc = (p) => {
const { sources, link1, link2 } = parseSourcesFromURL(window.location.href)
const redirect = `${p ? link1 : link2}?${sources.join('&')}`
const mixpanelTrackingData = getTrackingData(sources, p, redirect)
mixpanel.track('Button Clicked', mixpanelTrackingData, () => {
window.location.href = redirect;
})
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
module.exports = {
....
};
else
window.utmSourcesToObject = utmSourcesToObject;
window.parseReferrerForLinksAndUTM = parseReferrerForLinksAndUTM;
window.redirectBasedOnAge = redirectBasedOnAge;
})();
js/scripts.test.js
const { redirectFunc, parseSourcesFromURL } = require('./js/scripts')
const testURL = 'https://test.com/'
describe('parseReferrerForLinksAndUTM', () => {
beforeEach(() => {
global.window = Object.create(window)
Object.defineProperty(window, 'location', {
value: { href: testURL },
writable: true
})
### THIS DOESNT WORK ###
Object.defineProperty(window, 'mixpanel', {
track: jest.fn()
})
})
const { sources, link1, link2 } = parseSourcesFromURL(testURL)
test('redirect link is correct', () => {
### THIS DOESNT WORK ###
global.mixpanel = Object.create({})
global.mixpanel.track = jest.fn()
expect(link1).toBe('https://link1.com')
})
})
解决方案
推荐阅读
- wordpress - Functions.php 使用 rel:="nofollow" 设置所有外部链接
- sql - 创建这两个表或添加外键约束时出错
- c++ - 如何将非静态成员函数用于模板参数?
- python - 调整方法在 Pandas ewm() 函数中如何工作?
- android - React Native 错误:Android 上的 spawnSync adb ENOENT 错误
- codesys - 使用 FB_Init 方法保留功能块
- sql - 在公式中组合度量和维度 (Datastudio)
- angular - Angular 材质树中的对象数组
- reactjs - ThreeJS Gltf 已加载,但模型不可见(生产版本)
- sql - SQL。有限查询