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

Jam*_*mie 7 javascript unit-testing jasmine

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

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

function Y(arg) {
  return 'Got empty string'
}
Run Code Online (Sandbox Code Playgroud)

我想在测试中做什么

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')
  })
})
Run Code Online (Sandbox Code Playgroud)

对于这些类型的问题的更一般的答案,如果“如果Y,则执行X”会很棒。谢谢 :)

Fau*_* NA 5

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

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

function Y(arg) {
  return 'Got empty string'
}
Run Code Online (Sandbox Code Playgroud)

您的测试:

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')
  })
})
Run Code Online (Sandbox Code Playgroud)

值得注意的是,将 window 对象用于此类事情并不是最好的方法。如果你想像这样使用间谍,你应该创建一个对象来保存你的方法。

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