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/