简体   繁体   English

Jasmine 测试 - 间谍定义错误

[英]Jasmine testing - Error upon spy definition

I have the following classes我有以下课程

export class Init {
   constructor(url: URL) {}
   
   getClient(url: URL): Client {
    return new Client(url);
  }
}

and the client is defined like客户被定义为

export class Client {
   constructor(readonly url: URL) {}

   foo(s: String): Promise<void> {}

   // many other methods
}

and now I am trying to test this like so - with Jasmine现在我正在尝试这样测试 - 使用 Jasmine

it('foo should be invoked', done => {
   const init = new Init('test-url');
   
   spyOn(init.getClient,'foo');

   ...
}

On the spy definition I get this error在间谍定义中我得到这个错误

Argument of type 'string' is not assignable to parameter of type 'never'

Why can I resolve this?为什么我可以解决这个问题? Init 's getClient method returns a Client object. Shouldn't the spy be able to identify this type? InitgetClient方法返回一个Client object。间谍应该不能识别这种类型吗?

My end result should look like this我的最终结果应该是这样的

it('foo should be invoked', done => {
   const init = new Init('test-url');
   
   spyOn(init.getClient,'foo');

   expect(initCommand.getClient.foo).toHaveBeenCalledTimes(1);
}

You can only spyOn public methods.您只能spyOn公共方法。 I would do this:我会这样做:

// mock `getClient` object however you like (some examples below)
// Return the object/value right away
spyOn(init, 'getClient').and.returnValue({ foo: (s: string) => Promise.resolve(s) });
// call a fake function every time init.getClient is called
spyOn(init, 'getClient').and.callFake((url) => return {});

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

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