簡體   English   中英

節點 ts-jest spyOn 方法不匹配重載

[英]node ts-jest spyOn method does not match overload

我正在嘗試將 Jest 與ts-jest結合使用來為 nodeJS 服務器編寫單元測試。 我的設置與以下非常相似:

impl.ts

export const dependency = () => {}

索引.ts

import { dependency } from './impl.ts';
export { dependency };

消費者.ts

import { dependency } from '../impl' <- importing from index.ts
export const consumer = () => {
  try {
   dependecy();
   return true;
  } catch (error) {
    return false;
  }
}

消費者.test.ts

import * as dependencies from '../impl'
import { consumer } from './consumer'
const mockDependency = jest.spyOn(dependencies, 'depenedncy');
describe('function consumer', function () {
  beforeEach(function () {
     mockDependency.mockReturnValueOnce(false);
  });

  test('should return true', () => {});
})

這只是玩具代碼,但實際的導出/導入/測試文件遵循類似的結構。 我在這些方面收到 typescript 錯誤:

TS2769: No overload matches this call. 具體來說,被監視的方法不是依賴項導入重載的一部分,所以我不能把它存根。 我在不同的測試文件中做同樣的事情,它沒有問題。 有人知道如何解決打字問題嗎?

問題出在依賴 function 本身的類型上。 返回值鍵入不正確,這就是導致 Typescript 錯誤的原因。 基本上我有這個:

export const dependency: Handler = () => {
  return () => {} <- is of type Handler
}

而不是這個

export const dependency = (): Handler => {
  return () => {} <- is of type Handler
}

愚蠢的錯誤,希望它在未來對其他人有所幫助。 我的收獲是,如果您遇到沒有意義的類型錯誤,請確保檢查所有涉及的變量的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM