我应该如何为使用 Karma、Mocha 和 Sinon 的 promise 的 JavaScript 前端服务编写单元测试

How should I write a unit test forJavaScript frontend service that uses promise with Karma, Mocha and Sinon

尝试测试我正在编写的一些与第三方交互的服务API并想知道如何有效地测试它。

我有下一个方法:

    function getMemberProfile(memberId) {

        //Make sure memberId is defined and that it is a number
        if (!isNaN(memberId)) {
            return Client.authorizedApiRequest('/members/' + memberId).get();
        }
        return Promise.reject(new Error('Proper memberId was not supplied'));
    }

当 Client.authorizedApiRequest('/members/' + memberId).get() 调用第 3 方 API 和 returns 解析为某个对象(即 {id :12,姓名:'John Doe'}).

那么,我该如何测试getMemberProfile函数呢?我正在考虑用 sinon 模拟 Client.authorizedApiRequest("some params").get() 但我无法让它工作。

谢谢

好的,成功了。首先,您需要安装 chai。然后,在您的规范文件中:

beforeEach(function () {
    fakeMember = {
        member: {
            id: 10002,
            first_name: 'John',
            last_name: 'Doe'
        }
    };
});

it('should get a member\'s profile by memberId', function () {

        //mock
        sinon.stub(Client, 'authorizedApiRequest').withArgs('/members/' + fakeMember.member.id).returns({
            get: function () {
                return Promise.resolve(fakeMember);
            }
        });

        return Members.getMemberProfile(fakeMember.member.id).then(function (response) {
            expect(response).to.have.property('member');
            expect(response.member).to.have.property('id', fakeMember.member.id);
            expect(response.member).to.have.property('first_name', fakeMember.member.first_name);
            expect(response.member).to.have.property('last_name', fakeMember.member.last_name);
        });

});