简体   繁体   中英

why jasmine spy return a function?

I started messing around with jasmine but I'm having trouble with this code:

describe('UserService with errorsServiceSpy and testbed', () => {
    //how to test service that depends by another service
    let userService: UserService;
    let errorsServiceSpy: jasmine.SpyObj<ErrorsHandlerService>;

    beforeEach(() => {
        const spy = jasmine.createSpyObj('ErrorsHandleService', ['getErrors', 'addError']);

        TestBed.configureTestingModule({
            providers: [
                UserService, { provide: ErrorsHandlerService, useValue: spy }
              ]
        });

        userService = TestBed.inject(UserService);
        errorsServiceSpy = TestBed.inject(ErrorsHandlerService) as jasmine.SpyObj<ErrorsHandlerService>;
    });

    it('should be created', () => {
        expect(userService).toBeTruthy();
    });

    it('should return user', () => {
        expect(userService.getUser).toBe(userService.user)
    })

    it('#getErrors should return #error value from a spy', () => {
        const error:string = 'prova errore';
        userService.generateError(error)
        let errors:any = errorsServiceSpy.getErrors.toString()
        console.log('errors', errors)
        expect(errorsServiceSpy.getErrors.toString()).toContain(error)
    });

})

I state that without testBed or with testBed without spy I can test. But when I use the spy errorsServiceSpy.getErrors.toString () which should return an array in string, it returns a function: '

function() {
    return fn.apply(this, arguments);
}

look at all the code in the stackblitz !
pay no attention to the failed test due to 'this.errorsService' I think it's a stackblitz issue

Why it return me a function? How to test the service's method? WHit testBed and spy?
if you need more details I am at your complete disposal

You're thinking about it wrong, you don't want to get the errors, you want to know if your method has been invoked with a particular parameter, so:

let errors:any = errorsServiceSpy.getErrors.toString()
expect(errorsServiceSpy.getErrors.toString()).toContain(error)

Should be:

expect(errorsServiceSpy.getErrors).toHaveBeenCalledWith(error);

Though you don't actually show what getErrors does so the actual implementation will vary. I'd suggest you read the docs

Also please be consistent with the semi colons in your code

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