2

I create dynamically a request string in my react application, passing it to axios.get to request some data from REST interface. In my react test, I mock axios with

axios.get.mockResolvedValue({
  data: {
    list: [
      { name: "Name 1", id: 0 },
      { name: "Name 1", id: 0 }
      etc
    ]
  }
})

Which gives me always a static result - which is fine. But now, I also want to test depending on the dynamically created search term, so the question is: How do I get the request string/parameter from axios.get function in my mock?

boiler
  • 140
  • 10
  • 1
    [`.mockImplementation`](https://jestjs.io/docs/mock-function-api#mockfnmockimplementationfn)? Note that I'd generally recommend [not mocking axios](https://stackoverflow.com/a/67107497/3001761). – jonrsharpe May 12 '21 at 13:29
  • Not sure if axios changes the interface often but basically you have this "issue" always with 3rd party libraries. I'm don't think it is a good idea to move always a interface in, because of possibility that something might change. But mockImplementation was helpful. Thx. – boiler May 25 '21 at 08:12
  • Yes, you do, and I'm not saying you shouldn't also do that with other interfaces you don't own. And the possibility that something might change is exactly _why_ you do that, to insulate your implementation from those changes. Sure you might never actually change from Axios to e.g. fetch and their APIs might be perfectly stable, but considering that possibility leads you to less tightly coupled, more testable and more maintainable code; if those changes _do_ happen, you only have to change your code in one place. – jonrsharpe May 25 '21 at 08:25
  • I get your point but I'm pretty sure you didn't get maintable code when you add bloat and this is the case when you add interfaces that just forward calls to avoid changes in 3rd party libs somewhere in future. You also didn't know the changes so there is no guarantee that your interface will work. My approach is to abstract on another level, so there is only one place for the mocks. – boiler May 25 '21 at 10:21
  • *"You also didn't know the changes so there is no guarantee that your interface will work"* - your interface is driven by _what your code needs_, not the details of how the dependency provides that, that's the whole point. It doesn't need to be very heavyweight, e.g. look at https://github.com/textbook/fauxauth/commit/21c31aba3d4c12eb92a94aba2fccc0ea98715d20#diff-c07b115211c4d6ff449d71a1ec0f8ab5c9151b140a654fc38a6060fb57852232 where the function parameters don't change, but how we use them does. – jonrsharpe May 25 '21 at 10:43

0 Answers0