首页 > 解决方案 > 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')
  })
})

标签: javascriptmockingjestjsmixpanel

解决方案


推荐阅读