Unit testing with fakes

I’m trying to unit test a function similar to the example below and I need to fake the query to return a suitable response

function( id )  {

    const response = Order.query()
        where( foobar, id)
        first()

    ...
    ... ...

    if( response ) {

        Event::fire(my::event)
    }
}

I’m trying to fake the query with the following code but to no avail. The actual method is called.

test("mytest", async ({ assert }) => {

    Event.fake();

    ioc.fake('App/Models/Order', () => {
        return {
            query () {
                return "gotcha";
            
            }
        }
    })


    ...
    ... ...

}).timeout(0);

Is it possible? Can anybody please advise on my mistake?

1 Like

Why do you want to fake a database query?

@olaoluwa-98 I want to test the logic that comes after the query and ensure I return the orrect dataset. I could easily refactor the code and probably should to pass in the dataset as a parameter but wondered if it is possible to mock the query?

I’m not sure if mocking the query is good practice. Why can’t you call the actual query and test what comes after. I believe mocking is used for third party APIs that you cannot be calling every time you run tests

1 Like

In that you are right: mock only the objects you own. @olaoluwa-98

I’m unit testing a method and therefore don’t want to talk to the DB. Must be tested in isolation. Probably best refactoring my solution to accept the dataset as a parameter and create a pure function.

Thanks.

1 Like