测试不返回任何值的方法(茉莉角4)

Ank*_*har 7 jasmine karma-jasmine angular

我正在使用茉莉花进行测试的项目中。我遇到一种情况,方法不返回任何值,而只是设置类属性。我知道如何在返回值的方法上使用间谍,但不确定如何在不返回任何值的方法上使用间谍。我在网上搜索但找不到任何合适的资源。并且方法如下

updateDvStatus() {
    this._http.get(this.functionControlUrl).subscribe(() => {
    this._active = true;
    }, (error) => {
      this.errorStatusCode = error.status;
      this.errorPageService.setStatusCode(this.errorStatusCode);
    })
  }
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

Set*_*ers 6

如何测试不返回任何内容的方法

以下是测试不返回任何内容的方法的示例。

var serviceUnderTest = {
  method: function() {
    console.log('this function doesn't return anything');
  }
};

it('should be called once', function() {
  spyOn(serviceUnderTest, 'method');

  serviceUnderTest.method();

  expect(serviceUnderTest.method.calls.count()).toBe(1);
  expect(serviceUnderTest.method).toHaveBeenCalledWith();
});
Run Code Online (Sandbox Code Playgroud)

如何测试回调

我怀疑您的真正问题是,尽管正在测试要传递给subscribe()函数的函数是否达到了您的期望。如果是您真正要问的问题,那么以下内容可能会有所帮助(请注意,我是在脑海中写下这句话的,因此可能有错字)。

var serviceUnderTest = {
  method: function() {
    this.someOtherMethod(function() { this.active = true; });
  },
  someOtherMethod: function(func) {
    func();
  }
}

it('should execute the callback, setting "active" to true', function() {
  spyOn(serviceUnderTest, 'someOtherMethod');

  serviceUnderTest.method();

  expect(serviceUnderTest.someOtherMethod.calls.count()).toBe(1);
  var args = serviceUnderTest.someOtherMethod.calls.argsFor(0);
  expect(args.length).toBeGreaterThan(0);
  var callback = args[0];
  expect(typeof callback).toBe('function');

  expect(serviceUnderTest.active).toBeUndefined();
  callback();
  expect(serviceUnderTest.active).toBe(true);
});
Run Code Online (Sandbox Code Playgroud)

您的方案

抱歉,使用较旧的语法,我是从脑海写的,所以我宁愿它能正常工作,而不是看起来很酷,但有一些错别字。另外,我还没有使用过Observables,因此可能有比我要向您展示的更好的方法来测试它们,这可能相当于创建了一个新的Observable,并监视了订阅。由于这是我的头等大事,我们将不得不做。

it('should subscribe with a function that sets _active to true', function() {
  // Arrange
  var observable = jasmine.createSpyObj('Observable', ['subscribe']);
  spyOn(http, 'get').and.returnValue(observable);

  // Act... (execute your function under test)
  service.updateDvStatus();

  // Assert
  expect(http.get.calls.count()).toBe(1);
  expect(http.get).toHaveBeenCalledWith(service.functionControlUrl);
  expect(observable.subscribe.calls.count()).toBe(1);
  var args = observable.subscribe.calls.argsFor(0);
  expect(args.length).toBeGreaterThan(0);
  var callback = args[0];
  expect(typeof callback).toBe('function');

  service._active = false;
  callback();
  expect(service._active).toBe(true);
});
Run Code Online (Sandbox Code Playgroud)