0

How can I test optional chaining in jest?
Should I?

Comments
  • 0
    as long as the expected outputs/sideeffects match the given inputs/mocked state, you don't need to test the inner workings
  • 0
    @localpost but it drops the test coverage if I don't as it leaves an untested branch.
    The current requirement is for a 100% coverage. Which, might be overkill but it will drop down once the project progresses.
  • 0
    @localpost my current solution was to switch to an if-statement and write the test. Although I am curious on how optional chaining can be tested.
  • 1
    @boomgoat I hate this whole "100% test coverage schtick. Can't we just use good, static languages that can't break arbitrarily at any moment because of forgotten manual type checks
  • 1
    @boomgoat the only two branches would be "left side of ?. is undefined" or "it isn't", right? can you not set up tests for both scenarios?
  • 1
    @12bitfloat I mean it does have it's perk but I get what you're saying. I think the optimum scenario varies from case to case but I guess 80% is the sweet spot.
  • 0
    @localpost I was trying to keep it as compact as possible but you're right. Although I ended up switching to an if statement. After reading your comment I realized I just added a few pointless lines of code. πŸ˜…
    Added a custom 400 response because of the if though. Already pushed the code and created the PR. So it's all good anyway. πŸ˜…
  • 1
    Any metaprogramming available?

    If they all return self, you can make an array of all possible chain functions, and just call all of them in order.

    For a ridiculously thorough test, run all permutations of them. Beware, it’s O(n^2).

    Ruby/RSpec implementation:
    ```
    # linear
    methods = [:foo, :bar, :baz]
    object = whatever()
    methods.each do |method|
    expect {
    object = object.public_send(method)
    }.to_not raise_exception
    end
    ```

    For args, use a hash (dict/json) instead.
  • 1
    @Root this is a typescript question
  • 0
    @Root I am confused
  • 1
    @localpost Just an example. I don’t know how to do the same in JavaScript off the top of my head.
  • 0
    You shouldn't, Microsoft have (hopefully) already tested it. Don't test twice.
Add Comment