Vue.js 如何使用Sinon.js(vue)存根/模拟返回值以测试我的方法

Vue.js 如何使用Sinon.js(vue)存根/模拟返回值以测试我的方法,vue.js,mocking,jestjs,sinon,stubbing,Vue.js,Mocking,Jestjs,Sinon,Stubbing,我尝试了这么多代码,但没有人在我的情况下工作 // returns all groups from DB getAllGroups() { apiService.getAllGroups().then((data) => { this.groups = data; }) .catch((error) => { con

我尝试了这么多代码,但没有人在我的情况下工作

 // returns all groups from DB
        getAllGroups() {
            apiService.getAllGroups().then((data) => {
                this.groups = data;
            })
                .catch((error) => {
                    console.log(error.response.data.message);
                });
        },

如何为数据伪造一个值来测试getAllGroups方法

这是单元测试解决方案,您可以使用
jest.mock()
jest.spyOn()
来模拟或监视
apiService.getAllGroups
方法

group.js

从“/apiService”导入apiService;
班级{
组=[];
getAllGroups(){
回程服务
.getAllGroups()
。然后((数据)=>{
这个组=数据;
})
.catch((错误)=>{
日志(错误、响应、数据、消息);
});
}
}
导出默认组;
apiservice.js

const-apiService={
异步getAllGroups(){
返回[];
},
};
出口服务;
group.test.js

从“/Group”导入组;
从“/apiService”导入apiService;
描述('59591410',()=>{
之后(()=>{
开玩笑。恢复记忆();
});
它('应该正确地获取所有组',异步()=>{
jest.spyOn(apiService,'getAllGroups').mockResolvedValueOnce([1,2]);
常量组=新组();
wait group.getAllGroups();
expect(group.groups).toEqual([1,2]);
});
它('应该处理错误',异步()=>{
const error={响应:{数据:{消息:'some error'}};
jest.spyOn(apiService,'getAllGroups').mockRejectedValueOnce(错误);
玩笑间谍(控制台,'日志');
常量组=新组();
wait group.getAllGroups();
expect(console.log).toBeCalledWith('someerror');
});
});
单元测试结果和覆盖率报告:

PASS src/stackoverflow/59591410/group.test.js
59591410
✓ 应正确获取所有组(10毫秒)
✓ 应处理错误(6ms)
console.log node_modules/jest mock/build/index.js:860
一些错误
---------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
---------------|----------|----------|----------|----------|-------------------|
所有文件| 92.31 | 100 | 80 | 91.67 ||
apiservice.js | 66.67 | 100 | 0 | 66.67 | 3|
group.js | 100 | 100 | 100 | 100 ||
---------------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:6.114秒,估计12秒
源代码: