Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async/await mocking

I was wonder if one can do something like this with async/await in tests.

With regular promises I can for example mock out a promise in unit test like this.

class Foo {
    fn() {
        this.someService.someFn().then((data) => this.data = data);
    }
}

describe("something", function() {
    beforeEach(function() {
        this.instance = new Foo();

        // Can this part be mocked out with the same idea, when someService.someFn is async fn
        this.instance.someService = {
            someFn: function() {
                return {
                    then: function(cb) {
                        cb("fake data");
                    }
                }
            }
        }

        this.instance.fn();

    });

    it("a test", function() {
        expect(this.instance.data).toBe("fake data");
    });
});

(If I overwrite the promise I don't have to deal with flushing or anything like that.) But now, when fn() will change to this

class Foo {
    async fn() {
        try {
            this.data = await this.someService.somefn();
        } catch() {

        }
    }
}

The overwrite I did in the beforeEach will not work anymore. So my question here is...Can I do something like what I did with promise overwrite with async/await code style.

Idea here is that I want to mock out outside dependencies what a function that I am unit testing might use, like "someService" is. In that specific unit test I expect someService.someFn to work properly and I can mock out its response. Other test check the validity of "someFn".

like image 944
Kapaacius Avatar asked Jan 06 '23 19:01

Kapaacius


1 Answers

First of all, your old mock should work perfectly fine with async/await. Though, it's better to use Promise.resolve instead of returning an object with .then method:

someFn: () => Promise.resolve('fake data')

But since you're already using async/await, you could take advantage of it in your tests as well:

someFn: async () => 'fake data'
like image 190
Leonid Beschastny Avatar answered Jan 12 '23 00:01

Leonid Beschastny