简体   繁体   中英

How do I reach a callback within a Promise for testing using Mocha and Sinon?

Here's the function I'm trying to test:

write(filename, content, theme) {
    return new Promise((resolve, reject) => {
        let filePath = path.resolve(this.config.output.path, this.defineFilename(filename, theme, content));
        fs.writeFile(filePath, content, e => {
            if (e != null) reject(e);
            this.addToManifest(filename, filePath, theme);
            resolve(filePath);
        });
    });
}

Here's what I've got so far, but I'm missing something in my understanding. I don't understand what to put in the callbacks in my test.

        it('should reject the promise if there is an error', () => {
            const sandbox = sinon.sandbox.create();
            var expectedError = function(e) {

            };
            sandbox.stub(fs, 'writeFile', (filePath, content, expectedError) => {

            });

            sandbox.stub.onCall(0).returns('Hello');

            return instance.write(filename, content, theme).then((data) => {
                console.log('should not get to this line');
                expect(data).to.not.be.ok;
                sandbox.restore();
            }).catch((err) => {
                expect(err).to.be.an('error');
                sandbox.restore();
            });
        });

Finding documentation with examples for sinon.js has been challenging, also. Any suggestions there? Thank you for your help!

I think, to simulate an error in writeFile, it should be :

sandbox.stub(fs, 'writeFile', (filePath, content, callback) => {
    callback(new Error())
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM