验证setter已在ts-mock中调用



Location定义如下:

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

假设我有一个这样的服务:

export class MyService {
constructor(private readonly location: Location) {}
public myMethod(search: string): void {
this.location.search = search;
}
}

和一个测试用例:

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

我如何验证search的setter已经被调用了正确的值?

幸运的是,在这种情况下,this.location.assign(`${this.location.pathname}?${search}`);似乎与MyService中的this.location.search = search;大致相同,只要search不是空的。

修改后,我可以这样测试它:

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

相关内容

  • 没有找到相关文章

最新更新