如何使用Sinon

时间:2016-12-19 16:59:54

标签: jquery ajax sinon

我有一个函数向端点发出AJAX请求并获取JSON,我如何使用Sinon伪造该AJAX请求以便我可以测试该函数是否正常工作?

1 个答案:

答案 0 :(得分:5)

如果您使用[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin-2.4.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.975 s [INFO] Finished at: 2017-04-19T15:45:25+05:30 [INFO] Final Memory: 8M/155M [INFO] ------------------------------------------------------------------------ [ERROR] Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-install-plugin:jar:2.4: Could not transfer artifact org.apache.maven.plugins:maven-install-plugin:pom:2.4 from/to central (https://repo.maven.apache.org/maven2): Unexpected response code for CONNECT: 405 -> [Help 1] Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Could not transfer artifact org.apache.maven.plugins:maven-install-plugin:pom:2.4 from/to central (https://repo.maven.apache.org/maven2): Failed to transfer fil : https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.4/maven-install-plugin-2.4.pom. Return code is: 405 , ReasonPhrase:Method Not Allowed. ,则可以将其存储为:

jQuery.ajax()

然后编写测试用例。

最后,您应该恢复原始var returnData = {name: 'value'} var stub = sinon.stub($, 'ajax'); stub.yieldsTo('success', returnData); 功能,如下所示:

jQuery.ajax()