Jasmine Spy of Function inside Function async

65 Views Asked by At

I have a function (functionUnderTest) that calls another function (functionToTest). Both return an observable. I want to test if the function functionToTest is called when functionUnderTest is called. Therefore the functions are not in the same .ts file.

File1.ts:

export function functionUnderTest(value): Observable<string> {
    return functionToTest(value);
}

File2.ts:

export function functionToTest(value): Observable<string> {
  return of(value);
}

FYI: It is for my Angular 16 project

My testcode example:

import { functionUnderTest} from './File1';
import * as File2 from './File2';

describe("Test Suite", () => {
  it("test Function with spy", () => {

    spyOn(File2, 'functionToTest').and.callThrough();

    functionUnderTest('test parameter').subscribe(() => {

      expect(File2.functionToTest).toHaveBeenCalled();
      expect(File2.functionToTest).toHaveBeenCalledWith('test parameter');

    });
  });
}); 

The issue is, I get the Error:

Error: <spyOn> : functionToTest is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)

Found a solution

When I add

"module": "commonjs",

To the tsconfig.spec.json-File inside the "compilerOptions" this will work!

0

There are 0 best solutions below