我有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则执行X”会很棒。谢谢 :)

最佳答案

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

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')
  })
})

值得注意的是,将window对象用于此类操作并不是最佳方法。如果要使用这样的 spy ,则应在保存方法的地方创建一个对象。

Jasmine spy 文件:https://jasmine.github.io/2.0/introduction.html#section-Spies

10-01 05:50
查看更多