简体   繁体   English

验证 setter 已在 ts-mockito 中调用

[英]Verify setter has been called in ts-mockito

Location is defined as follows: Location定义如下:

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?我将如何验证是否已使用正确的值调用了search设置器?

Luckily, in this case this.location.assign(`${this.location.pathname}?${search}`);幸运的是,在这种情况下this.location.assign(`${this.location.pathname}?${search}`); seems to be about the same as this.location.search = search;似乎与this.location.search = search; in MyService as long as search is not empty.MyService中只要search不为空。

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();
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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