javascript - 如何使用 mocha/jest 模拟/测试事件监听器?

标签 javascript testing mocha.js jestjs

class Router {
    constructor() {
        window.onhashchange = this.hashChange;
    }

    hashChange() {
        console.log('Hash Changed');
        return true;
    }
}

export default Router;

我正在尝试找到一种方法来在node.js 中测试上述代码。但是node中没有window对象。如何使用 mocha/jest 模拟对象并测试事件监听器?目标是测试当 URL 哈希值更改时 hashChange() 是否被调用

最佳答案

default test environment Jest 中是 jsdom 提供的类似浏览器的环境。

jsdom 提供 window,因此默认情况下可用于在 Jest 中运行的测试。

您可以使用Jest来测试上面的代码,如下所示:

class Router {
  constructor() {
      window.onhashchange = this.hashChange;
  }

  hashChange() {
      console.log('Hash Changed');
      return true;
  }
}

test('Router', () => {
  const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
  const router = new Router();
  window.onhashchange();
  expect(hashChangeSpy).toHaveBeenCalled();  // Success!
});

关于javascript - 如何使用 mocha/jest 模拟/测试事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55384258/

相关文章:

node.js - express 中间件测试 mocha chai

node.js - Mocha + Supertest 中 404 测试的“Body Parse”错误

python - 我可以用 Nose 嵌套测试用例吗?

python - 构造函数中的 Magic Mock 函数

c++ - Boost.Test如何进行测试?

javascript - 在 React 中使用 SetInterval 卸载组件

javascript - 如何通过单击每个链接进行循环并验证每个页面上的相同元素?

javascript - php中RGBA值的正则表达式

javascript - 如何在 sap.m.multiComboBox 中的 View 中设置默认值

javascript - 为什么我的文字不闪烁?