小编Rij*_*ijk的帖子

如何在 TypeScript 中包装的 addEventListener 调用中正确键入事件处理程序

我正在尝试在该addEventListener方法上编写一个抽象层,但遇到了打字问题。在下面的最小复制中;

function addEventListener<T extends EventTarget>(
  element: T,
  type: string,
  handler: EventListener
) {
  element.addEventListener(type, handler);
}

addEventListener<Window>(window, "mousedown", (event: MouseEvent) => {
  console.log(event.pageX);
});

Run Code Online (Sandbox Code Playgroud)

TypeScript 抱怨参数类型与 MouseEvent 不兼容:

Argument of type '(event: MouseEvent) => void' is not assignable to parameter of type 'EventListener'.
  Types of parameters 'event' and 'evt' are incompatible.
    Type 'Event' is missing the following properties from type 'MouseEvent': altKey, button, buttons, clientX, and 20 more.
Run Code Online (Sandbox Code Playgroud)

我知道以下(基本)事件侦听器:

Argument of type '(event: MouseEvent) => void' is not …
Run Code Online (Sandbox Code Playgroud)

javascript addeventlistener typescript typescript-typings

6
推荐指数
1
解决办法
3128
查看次数

如何对独立的 Vue 组合进行单元测试

我有一个类似于文档的示例的设置,其中我的组合位于与我的组件不同的文件中,如下所示:

// composition.js
import { onMounted } from '@vue/composition-api';

export default function useComposition() {
  onMounted(() => {
    console.log('Hello, world!');
  });
}
Run Code Online (Sandbox Code Playgroud)
// component.vue
<template>...</template>

<script>
import { createComponent } from '@vue/composition-api';

export default createComponent({
  setup() {
    useComposition();
  }
})
</script>
Run Code Online (Sandbox Code Playgroud)

我想为该composition.js文件编写一个单独的(基于 Jest 的)测试文件。但是,直接调用组合时,Vue 会报错(意料之中):

// composition.test.js

import useComposition from './composition';

describe('Composition', () => {
  it('Works', () => {
    useComposition();
    // Error: [vue-composition-api] "onMounted" get called outside of "setup()"
  });
});
Run Code Online (Sandbox Code Playgroud)

我已经尝试安装一个基于模拟组合 API …

vue.js jestjs vue-test-utils vue-composition-api

4
推荐指数
1
解决办法
1873
查看次数