Sinon delay callback function

Viewed 295

I simply want to simulate delayed callback function. I am using sinon and mocha for testing. I changed readFile of standart fs library. I want the yields function to be executed after 5 seconds. Thus, the callback function will run after 5 seconds. But It didnt work. It worked when I run the yields function before the fs.readFile function.

function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

it.only('test stıb',  async () => {
    const stub = sinon.stub(fs, 'readFile');
    stub.withArgs('path', 'utf8');

    fs.readFile("path", "utf8", (err, data) => {
        console.log(data);
    });
    await sleep(5000);
    stub.yields(null, "Read File Message");
    stub.restore();
});
1 Answers

It just seems like order of operations issue in your test.

.yields to to set up the behavior of your stub. Mocking after you already called the function you are trying to test is backwards.

function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

it.only('test stıb',  async () => {
    const stub = sinon.stub(fs, 'readFile');
    stub.withArgs('path', 'utf8');
    stub.yields(null, "Read File Message");

    await sleep(5000);

    fs.readFile("path", "utf8", (err, data) => {
        console.log(data);
    });

    stub.restore();
});
Related