<spyOn> : <functionName> is not declared writable or has no setter

Viewed 2903

I am trying spy an exported function with jasmine and angular. I am importing that function into my test file with the pattern: import * as HelperObject from '../file-parse' to have an object to spy on and then specify its exported function to create the spy. So, I have

file-to-test.spec.ts

import * as ParseHelper from './file-parser';

describe('ParserWorker', () => {
    it('should do something', () => {
       const mockResponse: CustomType = new CustomType()
       const spy = spyOn(ParseHelper, 'parser').and.returnValue(mockResponse)
    })
})

In file-parser.ts file I have this exported function

export function parser(fl: File, hd: boolean = false): CustomType{
    ... do something

    return CustomTypeObject;
}

When I run this test Karma show me this error:

Error: <spyOn> : parser is not declared writable or has no setter

I used this way to spy an individual exported function with no problem, notice that those functions are not any angular components or services, it just a class helper that has some functions that I need to pass to a web worker.

1 Answers

like this site, if your file-parser is single function, you can do like this.

add default declaration

export function parser(fl: File, hd: boolean = false): CustomType{
    ... do something

    return CustomTypeObject;
}

export default parser

and spyOn change 'parser' to 'default'

import * as ParseHelper from './file-parser';

describe('ParserWorker', () => {
    it('should do something', () => {
       const mockResponse: CustomType = new CustomType()
       const spy = spyOn(ParseHelper, 'default').and.returnValue(mockResponse)
    })
})
Related