【问题标题】:How do I reach a callback within a Promise for testing using Mocha and Sinon?如何在 Promise 中实现回调以使用 Mocha 和 Sinon 进行测试?
【发布时间】:2016-11-03 13:53:05
【问题描述】:

这是我要测试的功能:

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 示例的文档也很困难。那里有什么建议吗?感谢您的帮助!

【问题讨论】:

    标签: javascript callback promise sinon


    【解决方案1】:

    我认为,要模拟writeFile中的错误,应该是:

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

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2013-09-06
    • 2015-12-01
    • 2019-05-24
    • 2017-10-07
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多