What is the best practice for mocking nested functions for testing?

I will simplify my use case and implementation to make my question brief.

There are 3 functions in my lib.rs

  1. fetch_words_from_database() -> Vec<&'a str>
  2. fetch_words_from_api() -> Vec<&'a str>
  3. find_intersection() -> Vec<&'a str>

I want to unit test find_intersection function so I have to mock functions 1 and 2. How to achieve that?

fn find_intersection() -> Vec<&'a str> {
        let words_database = fetch_words_from_database();
        let words_api = fetch_words_from_api();
        let words_api: HashSet<_> = words_api.into_iter().collect();
        
        let mut intersection: Vec<&'a str> = Vec::new();
        
        for word in words_database {
            if words_api.contains(word) {
                intersection.push(word)
            }
        }
        
        intersection
}

I am looking for something like jest.spyOn.

You can split it into two functions, one that accepts the result of fetch_words_from_api() and fetch_words_from_database(), then the actual find_intersection will just call into that more generic one.

You would need dependency injection here. i.e. find_intersection could receive fetch_words_from_database and fetch_words_from_api as arguments, so that you provide the exact implementation that you want.