Reactjs React模拟Graphql订阅
我有一个react项目,我正在使用Jest进行测试。我试图模拟对AWS graphql的调用,特别是对subscribe的调用。这是我试图模仿的代码Reactjs React模拟Graphql订阅,reactjs,unit-testing,graphql,jestjs,graphql-subscriptions,Reactjs,Unit Testing,Graphql,Jestjs,Graphql Subscriptions,我有一个react项目,我正在使用Jest进行测试。我试图模拟对AWS graphql的调用,特别是对subscribe的调用。这是我试图模仿的代码 await API.graphql( graphqlOperation(subscriptions.addedProduct)) .subscribe({ next: (response) => { this.setState({ products: [...this.state.products,
await API.graphql(
graphqlOperation(subscriptions.addedProduct))
.subscribe({
next: (response) => {
this.setState({ products: [...this.state.products, response.value.data.addedProduct] })
}
});
我通常用类似这样的东西来模仿使用spyOn
const mockProducts = jest.spyOn(API, 'graphql').mockImplementation(async () =>
Promise.resolve(mockResponse)
);
但是会得到错误
TypeError:_awsAmplify.API.graphql(…)。订阅不是函数
有人有过类似模拟订阅的例子吗?您需要将
API.graphql
的返回值模拟为反应式编程产生的可观察的。然后,您可以使用.subscribe
方法。下面的示例中,我使用rxjs
的操作符创建一个可观察的
例如
main.jsx
:
import React,{Component}来自'React';
从“/API”导入{API};
导出类MyComponent扩展组件{
建造师(道具){
超级(道具);
此.state={
产品:[],
};
}
异步组件didmount(){
等待API.graphql('graphqlOperation(subscriptions.addedProduct)')。订阅({
下一步:(响应)=>{
this.setState({products:[…this.state.products,response.value.data.addedProduct]});
},
});
}
render(){
返回我的组件;
}
}
main.test.js
:
从“/main”导入{MyComponent};
从“/API”导入{API};
从'rxjs'导入{of};
描述('61454572',()=>{
它('should pass',async()=>{
const mockResponse={value:{data:{addedProduct:'fake product'}};
const graphqlSpy=jest.spyOn(API,'graphql').mockImplementation(()=>{
返回(模拟响应);
});
常量包装器=浅();
expect(wrapper.state('products')).toEqual(['fake product']);
expect(graphqlSpy).toBeCalledWith('graphqlsoperation(subscriptions.addedProduct)');
graphqlSpy.mockRestore();
});
});
单元测试结果和覆盖率报告:
passstackoverflow/61454572/main.test.jsx(11.328s)
61454572
✓ 应通过(12毫秒)
----------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
----------|---------|----------|---------|---------|-------------------
所有文件| 88.24 | 100 | 83.33 | 86.67 |
api.js | 50 | 100 | 0 | 50 | 5-6
main.jsx | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:13.119秒