Verify setter has been called in ts-mockito

464 Views Asked by At

Location is defined as follows:

interface Location {
    ...
    search: string;
    ...
}

Let's say I have a service that looks like this:

export class MyService {
    constructor(private readonly location: Location) {}

    public myMethod(search: string): void {
        this.location.search = search;
    }
}

and a test case:

describe('MyService', () => {
    it('should set search on location', () => {
        const location = mock<Location>();
        const myService = new MyService(instance(location));

        const someSearch = 'a=1';

        myService.myMethod(someSearch);

        // verify that location.search has been set
    });
});

How would I verfiy that the setter for search has been called with the correct value?

1

There are 1 best solutions below

0
On

Luckily, in this case this.location.assign(`${this.location.pathname}?${search}`); seems to be about the same as this.location.search = search; in MyService as long as search is not empty.

After the change I was able to teste it like this:

describe('MyService', () => {
    it('should set search on location', () => {
        const location = mock<Location>();
        const myService = new MyService(instance(location));

        const someSearch = 'a=1';
        const path = '/somePath';

        when(location.pathname).thenReturn(path);

        myService.myMethod(someSearch);

        // verify that location.search has been set
        verify(location.assign(`${path}?${someSearch}`)).once();
    });
});