Check if the function is called when passing a specific parameter

I have two simple functions. The first function X either takes a number or a string. If it receives a number, I return it double, and if it receives a string, I call another function Y. How can I check if my function X performs function Y when it takes a string as a parameter?

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

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

What I want to do in my test.

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 codeHide result

A more general answer for these types of problems, where “do X if Y” would be awesome. Thank:)

+4
source share
2 answers

. , 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.imtqy.com/2.0/introduction.html#section-Spies

+2

Jasmine, Spies: https://jasmine.imtqy.com/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');
  })
})
Hide result

: jsFiddle

async 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();
    }

  })
})
Hide result

(), , , .

0

Source: https://habr.com/ru/post/1674412/


All Articles