Home > Enterprise >  Javascript conditionally call chained method
Javascript conditionally call chained method

Time:09-01

Is there a chance to conditionally run a chained method ?

I want to simplify this expression to be a one-liner but can't find a solution for the blocking .not. on the expect.

const checkSomething = (element, value = true) => {
  if (value) {
    expect(element).toBeVisible()
  } else {
    expect(element).not.toBeVisible()
  }
}

CodePudding user response:

You can use an immediately invoked arrow function to create a one-liner expression:

const checkSomething = (element, value = true) => {
  (e => value ? e : e.not)(expect(element)).toBeVisible()
}

This is basically the same as

const checkSomething = (element, value = true) => {
  const e = expect(element);
  (value ? e : e.not).toBeVisible()
}

CodePudding user response:

You can use a ternary operator.

const checkSomething = (element, value = true) => value ? expect(element).toBeVisible() : expect(element).not.toBeVisible()

CodePudding user response:

Not exactly an optional chaining, but if you define your construct as

const expectMaybe = (arg, val) => val ? expect(arg) : expect(arg).not;

then maybe you can write your oneliner as

const checkSomething = (element, value=true) => expectMaybe(element, value).toBeVisible();
  • Related