Javascript 使用Sinon,当http是一个属性时,如何模拟http.foo.get?

Javascript 使用Sinon,当http是一个属性时,如何模拟http.foo.get?,javascript,mocking,sinon,Javascript,Mocking,Sinon,我有一个我想测试的文件,带有一个应该被模拟的http客户端: schema.js: const { http } = require('@foo/http-client'); ....... const result = await http.foo('another-service').get('graphql', { query: ` { SomeResolver(clientId: "${args.clientId}") {

我有一个我想测试的文件,带有一个应该被模拟的
http客户端

schema.js

const { http } = require('@foo/http-client');
.......
const result = await http.foo('another-service').get('graphql', {
                query: `
    {
        SomeResolver(clientId: "${args.clientId}") {
            id
            start
            end
        }
    }
    `,
});
const sinon = require('sinon');
const mockHttp = sinon.mock(require('@foo/http-client'));
.........
mockHttp.expects('foo').returns({
    get: (x,y) => {
        // mock the response here
    },
});
我需要模拟
结果

schema.test.js

const { http } = require('@foo/http-client');
.......
const result = await http.foo('another-service').get('graphql', {
                query: `
    {
        SomeResolver(clientId: "${args.clientId}") {
            id
            start
            end
        }
    }
    `,
});
const sinon = require('sinon');
const mockHttp = sinon.mock(require('@foo/http-client'));
.........
mockHttp.expects('foo').returns({
    get: (x,y) => {
        // mock the response here
    },
});
TypeError:试图将未定义的属性foo包装为函数
是上述错误,这是有意义的,因为
http
已解构的

但是,如果我将
expects
行更改为:

mockHttp.expects('http').returns
我得到的错误是
TypeError:试图将对象属性http包装为函数
,这也是有意义的,因为
http
属性


正如您所看到的,我对
Sinon
非常陌生,但我的问题是,当
http
属性时,如何模拟
http.foo.get

据我所知,模拟是针对对象的,期望是针对函数的,每个函数一个

在您的环境中,您似乎可以:

const{http}=require('@foo/http-client');
const mockHttp=sinon.mock(需要('@foo/http-client').http);//注意,http
mockHttp.expects('foo')。返回({
获取:(x,y)=>{
//在这里模拟回答
},
});
http.foo().get();
mockHttp.verify();
如果需要对其他
http
函数设置期望值,可以重用
mockHttp
。如果您需要模块中其他地方的函数的期望值,则需要为声明它们的对象创建另一个mock,并
verify()
该另一个mock。(我就是这样理解的,如果你知道得更清楚,请有人纠正!)

在任何情况下,使用分解分配都不会改变
http
变量引用模块的
http
属性的事实。换言之:

const{http}=require('@foo/http-client');
console.log(http==require('@foo/http-client').http);//真的

谢谢。离开我的机器几个小时,但我稍后会检查。