繁体   English   中英

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

[英]Check if a function is called when a specific parameter is passed

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

对于这些类型的问题,更常见的答案是“做X如果Y”会很棒。 谢谢 :)

你必须创建一个间谍。 您甚至可以检查调用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')
  })
})

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

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

如果你使用的是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(); } }) }) 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM