检查传递特定参数时是否调用函数

时间:2017-04-09 10:22:12

标签: javascript unit-testing jasmine

我有2个简单的功能。第一个函数X接收数字或字符串。如果它收到一个数字,我返回它的double,如果它收到一个字符串,我调用另一个函数Y.如​​何测试我的函数X在接收字符串作为参数时是否调用函数Y?



function X(arg) {
  if (typeof (arg) === 'String') Y(arg)
  else return arg * 2
}

function Y(arg) {
  return 'Got empty string'
}




我想在测试中做些什么..



describe('A function X that checks data type', function() {
  it('should call function Y is argument is a string', function() {
    let arg = arguments[0]
    expect(Y is called if typeof(arg)).toEqual('string')
  })
})




对于这类问题的更一般的答案,如果Y'会很棒的。谢谢:))

2 个答案:

答案 0 :(得分:2)

你必须创建一个间谍。您甚至可以检查调用Y的参数。假设您全局定义了这些函数,它们属于窗口对象:

function X(arg) {
  if (typeof (arg) === 'String') Y(arg)
  else return arg * 2
}

function Y(arg) {
  return 'Got empty string'
}

您的测试:

describe('A function X that checks data type', () => {
  beforeEach(() => {
    spyOn(window, 'Y')
  })
  it('should call function Y is argument is a string', () => {
    // Call X with a string
    window.X('hello')
    // If you don't want to check the argument:
    expect(window.Y).toHaveBeenCalled()
    // If you want to check the argument:
    expect(window.Y).toHaveBeenCalledWitH('hello')
  })
})

值得注意的是,将窗口对象用于此类事物并不是最好的方法。如果你想使用这样的间谍,你应该创建一个你拿着方法的对象。

关于茉莉花间谍的文件:https://jasmine.github.io/2.0/introduction.html#section-Spies

答案 1 :(得分:0)

如果您使用的是Jasmine,则可以使用间谍:https://jasmine.github.io/2.0/introduction.html#section-Spies

function X(arg) {
  if (typeof (arg) === 'string') Y(arg);
  else return arg * 2;
}

function Y(arg) {
  return 'Got empty string'
}

describe('A function X that checks data type', function() {
  it('should call function Y is argument is a string', function() {
    spyOn(window, 'Y').and.callThrough();
    X('Hello');
    expect(window.Y).toHaveBeenCalledWith('Hello');
  })
})

点击这里的工作演示: jsFiddle

以下是处理异步Y函数的方法: jsFiddle - asnyc

function X(arg) {
  let deferred = {};
  let promise = new Promise(function(res, rej) {
    deferred.res = res;
    deferred.rej = rej;
  });
  if (typeof(arg) === 'string') {
    setTimeout(function() {
      deferred.res(Y(arg));
    }, 1000);
    return promise;
  } else {
    return arg * 2;
  }
}

function Y(arg) {
  console.log('Y with timeout');
  return 'Got empty string';
}

describe('A function X that checks data type', function() {
  it('should call function Y is argument is a string', function(done) {
    spyOn(window, 'Y').and.callThrough();
    let promise = X('Hello');
    if (promise instanceof Promise) {
      promise.then(function() {
        expect(window.Y).toHaveBeenCalledWith('Hello');
        done();
      });
    } else {
      done();
    }

  })
})

但是我建议将您的功能附加到某些对象(模块),以便更轻松地跟踪在何时何地调用的内容。

相关问题