typescript - 如何在模拟函数时允许部分 TypeScript 类型 - Jest、TypeScript

标签 typescript jestjs

我有一个函数,我想在 TypeScript 中模拟它以进行测试。在我的测试中,我只关心 jsonstatus .但是,当使用 Jest 的 jest.spyOn 时我的模拟函数的类型设置为返回 http Response类型。这很尴尬,因为这意味着我必须手动去实现一堆不相关和任意的函数和属性。

我怀疑有某种方法可以在这里使用部分类型,通过将返回类型覆盖为仅我关心的类型来允许更好和更有用的模拟。我该怎么做呢?

export function mockApi(json: object, status: number): void {
  jest.spyOn(
    myApiModule,
    'methodWhichReturnsAResponse'
  ).mockImplementation(() =>
    Promise.resolve({
      json: () => Promise.resolve(json),
      status,
      // Below here is to appease jest types (not needed for
      // testing purposes at the time of writing)
      headers: {
        has: (name: string) => true,
        // get, set, etc...
      },
      ok: true,
      redirected: false,
      // and about 10 other properties which exist on the Response type
      // ...
    }),
  );
}

最佳答案

您可以使用 as ...

export function mockApi(json: object, status: number): void {
  jest.spyOn(
    myApiModule,
    'methodWhichReturnsAResponse'
  ).mockImplementation(() =>
    Promise.resolve({
      json: () => Promise.resolve(json),
      status
    } as http.Response), // <-- here
  );
}
as关键字,用于类型转换,当用于将文字转换为类型 X 时,将允许您仅部分定义它,但您仍然可以进行类型检查,因为您无法定义不存在的 Prop 。

例子:
type X {
  a: number
  b: number
}

const x = { a: 2 } as X // OK
const y = { a: 3, c: 2 } as X // NOT OK, because c does not exist in X

关于typescript - 如何在模拟函数时允许部分 TypeScript 类型 - Jest、TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129718/

相关文章:

vue.js - JEST @vue/composition-api + Jest 测试套件运行失败 [vue-composition-api] 在使用任何函数之前必须调用 Vue.use(VueCompositionAPI)

AngularFireDatabase、Jest 和单元测试,如何创建可重用的类 stub ?

angular - ionic 3 音频直播比直播电台流慢

typescript - 为什么 TypeScript TypeMemberList 中的分隔符是分号而不是逗号?

javascript - 开 Jest - 在测试前解决 promise

reactjs - 不变违规 : Element type is invalid: expected a string (for built-in components) when testing with enzyme mount

node-inspector - 使用 node-inspector 调试 Jest 测试用例

javascript - aws - CloudFront createInvalidation() 方法参数在使用 promises 时出错

javascript - 如果数组的一个元素不为空而不使用迭代器,则返回 false - Typescript

javascript - 设置 Meteor、Vue 和 Typescript