【问题标题】:Jasmine testing - Error upon spy definition茉莉花测试 - 间谍定义错误
【发布时间】:2021-10-04 16:35:45
【问题描述】:

我有以下课程

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

客户端的定义如下

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

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

   // many other methods
}

现在我正在尝试这样测试 - 使用 Jasmine

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

   ...
}

在间谍定义中我得到了这个错误

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

为什么我可以解决这个问题? InitgetClient 方法返回一个 Client 对象。间谍不应该能够识别这种类型吗?

我的最终结果应该是这样的

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

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

【问题讨论】:

    标签: javascript testing jasmine karma-jasmine spy


    【解决方案1】:

    你只能spyOn公共方法。我会这样做:

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

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      相关资源
      最近更新 更多