简体   繁体   中英

node ts-jest spyOn method does not match overload

I'm trying to use Jest in conjunction with ts-jest to write unit tests for a nodeJS server. I have something set up very similar to below:

impl.ts

export const dependency = () => {}

index.ts

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

consumer.ts

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

consumer.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', () => {});
})

This is just toy code, but the actual export / import / test files follow a similar structure. I'm getting typescript errors along these lines:

TS2769: No overload matches this call. Specifically, that the method being spied on is not part of the overload of the import for dependencies, so I can't stub it out. I am doing literally the same thing in a different test file and it has no issues. Anyone know how to resolve the typing issue?

The issue turned out to be in the typing of the dependency function itself. The return value typing was incorrect and that was what was resulting in the Typescript error. Essentially I had this:

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

rather than this

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

Stupid mistake, hope it helps someone else in the future. My take away is that if you have a type error that doesn't make sense make sure you check the typing of all variables involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM