簡體   English   中英

如何在Promise中到達回調以使用Mocha和Sinon進行測試?

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

這是我要測試的功能:

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);
        });
    });
}

到目前為止,這是我所得到的,但是我的理解中缺少一些東西。 我不知道在測試中要在回調中添加什么。

        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();
            });
        });

使用sinon.js的示例查找文檔也很困難。 有什么建議嗎? 謝謝您的幫助!

我認為,要模擬writeFile中的錯誤,應該為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM