intern test not using configured registry requestProvider in dojo - dojo

I'm following this article to mock response in dojo.
My mocker is very similar to the one in the article except this:
registry.register(/\/testIntern/, function (url, options) {
return when({
value: "Hello World"
});
In my understanding, this should map to any request that contains "/testIntern" on the address.
My testcase is quite simple:
// similar to example
var testRest= new Rest("/testIntern", true);
testRest("").then(lang.hitch(this, function (data) {
assert.deepEqual("Hello World", data.value, "Expected 'Hello World', but got" + data.value);
}));
It really should be quite simple. But when I run this test, I got 404 Not Found. It looks like the REST call in the test doesn't try to use the mocking service. Why?

You are generally correct in your thought that registering a URL with dojo/request/registry should pass anything referencing that URL via dojo/request through your handler.
Unfortunately, dojo/store/JsonRest uses the dojo/_base/xhr module which uses dojo/request/xhr directly, not dojo/request. Any registrations created with dojo/request/registry (and any setting of defaultProvider) will unfortunately be lost on JsonRest.
You might want to have a look at dstore - its Rest store implements the same server requests as dojo/store/JsonRest but it uses dojo/request instead of being hard-coded to a specific provider. (dojo/request defaults to dojo/request/xhr in browsers anyway, but can be overridden via dojoConfig.requestProvider.) dstore contains adapters for translating between dstore's API and the dojo/store API, if you need to use it with widgets that operate with the latter.

Related

Create mocks in api functional testing with Symfony

I'm dealing with a problem I have in a Symfony 4 API functional tests. My functional tests consists in making requests to the API and analyze the response given. I've been working like this and works fine.
The problem comes with a new API method I'm implementing which needs the perform a request to an external service. I want to mock during my tests, but I don't know how can I create a mock that persists when the API receives the request from the functional test.
I've been thinking about something like create mocks which are always used in the test environment but I haven't found anything...
you can check in http-client service called url and if it compare your external api url return certain response, it will be look something like this:
$guzzleServiceMock = $this
->getMockBuilder(GuzzleHttp\Client::class)->disableOriginalConstructor()
->setMethods(['get'])
->getMock();
$guzzleServiceMock
->expects($this->any())
->method('get')
->with(
$this->stringContains('/external/api/route')
)
->willReturnCallback(
function ($uri, $options = []) {
return new Response(
200,
[],
'{"result": {
"status": "success",
"data": "fake data",
}}'
);
}
);
next step you will need to inject service into container, with this question you can look this repo, there are good examples of how this can be done: https://github.com/peakle/symfony-4-service-mock-examples/blob/master/tests/Util/BaseServiceTest.php
I'm not sure if I understand correctly, but if you'd like to mock an external API (meaning your application is connecting to another application on another server), one solution would be to actually lunch a mock server to replace your actual external server.
Either you implement such a mock server yourself or you use an existing solution such as http://wiremock.org/

Passing javascript variable to velocity variable templete

I have installed xwiki successfully and able to generate wiki pages using velocity template language.
Could anyone please tell me that how can I pass javascript varible to velocity templete. I have gone through few forums that I need to pass the parameter to server to get this but I have no idea. Please find the files below.
<script type="text/javascript">
function generateFunction()
{
var variable = document.getElementById('text').value;
}
</script>
#set($test = "variable")
$test
You have to make an ajax call from the client to the server.If you're using jquery, you would have something like:
$.post('/send/my/var', { 'variable' : value });
Without jquery, see this XmlHttpRequest documentation.
And then, on the server side, the /send/my/var URL should reach a template where you can do:
#set($test = $params.variable)
And you would do something useful with it on the server-side, like store it in the session, in the database, etc.
If you need to send back something from Velocity to Javascript, then you'll typically have to format JSON code, and add an asynchronous completion callback parameter to the ajax call:
$.post('/send/my/var', { 'variable' : value },
function(data)
{
// do something with data sent back from the server
});
It's also possible to have synchronous calls, that is to have javascript wait for the server response, but it's generally a bad idea to do so and I won't extrapolate on it here.
As a final note, you should also implement a proper error handling. With jQuery for instance, the syntax would be:
$(document).ajaxError(function(event, jqxhr, settings, message)
{
console.log(message);
});
It can't be done,
Apache Velocity template is a server side engine,
Meaning that on the server, Velocity will get the template and try to render, only after it finished to render the template, it will be returned to client which will execute client code as Javascript
Velocity alternative is freemarker, which I found similar question and answer , Question:
How to call freemarker function with param from javascript
Answer:
There's no way for the client side web browser code to call a server side Freemarker function

Pass data across Hapi JS application

I want to detect current selected language from a domain (like es.domain.com, de.domain.com) so I need to pass it to all non static route handlers and to all views.
To detect a language I need a request object. But global view context it is possible to update where request object is not accessible (in server.views({})). Also server.bind (to pass data to route handler) works only where request object is not accessible.
Hapi version: 11.1.2
You could try something like this:
server.ext('onPreResponse', function (request, reply) {
if (request.response.variety === 'view') {
request.response.source.context.lang = request.path;
}
reply.continue();
});
This will attach a lang data point to the context that is being sent into the view. You'll have to extract the lang from the url as request.path is probably not what you actually want.
Also, if you look here you'll see a few pieces of request data is made available to every view via reply.view() If the locale/language is available directly in one of those data points, or can be derived from them, you can skip the extension point approach entirely.
Again, this is assuming version 10+ of hapi. If you're using an older version, the extension point method is your best bet.

How to stub an external API for testing

I have a project that makes some calls to Twitter's API from the node.js server that I would like to test. However, I don't want to test the Twitter API (OAuth and the actual API I'm calling), so I thought it would be best to stub it out.
I found sinon.js that supports this supposedly. I have not found an example of how to do this and was wondering if this has been done before. And if so, seeing some sample code would really help.
What are you doing to call the API?
Imagine you use a method called api.call('url', function (error, response) {...}):
you can "fake" the callback with sinon, gently or whatever you like.
Example using gently:
gently.expect(api, 'call', function (url, callback) {
assert.equal(url, 'http://api.twitter.com/...');
callback(Error('Fake error'), null);
});

Mocking out AJAX calls with Dojo XHR

I'm attempting to mock the response of a dojo xhr request, but I haven't found a good solution.
Ideally, I'd like to see a solution similar to the jQuery mockjax plugin where I can set a specific call based on a url, e.g.:
$.mockjax({
url: '/restful/fortune',
responseTime: 750,
responseText: {
status: 'success',
fortune: 'Are you a turtle?'
}
});
My initial thought was to utilize the "/dojo/io/send" channel, but I haven't been able to get a modified response to be loaded after modifying the dojo Deferred object.
The other thought is to use a pass-through method that would determine if an actual xhr request should be made, e.g.:
function xhrRequest(xhrArgs) {
if(shouldMock) {
var fakeReturnJson = dojo.toJson({
howdy: "that's odd!",
isStrange: false
});
return fakeReturnJson;
} else {
dojo.xhr(xhrArgs);
}
}
Can someone tell me the best way to go about mocking dojo xhr calls?
Thanks!
It's an old question, but I think you should do your mocking using Sinon.js
However you will need to put the following:
has: { native-xhr2: false }
into your dojoConfig for it to work in 1.8
I haven't heard of any Dojo specific libraries similar to Mockjax. But what I think you could try is use Mockjax with Dojo. This should be pretty easy to do since all you'll have to do is use JQuery during development only for testing with Mockjax and then remove it once development is complete.
I use your second suggestion. Currently, I have a transport layer (simple js class) and 2 implementations (XhrTransport and MockTransport). I then switch in which I need without changing the widget code.
Widgets call the server with:
Controller.send(aServerCall);
where aServerCall is a simple value object with the server endpoint, params and callback.
This way, you can add nice things to the controller that will apply to all server calls (such as logging, analytics, generic error handling...) and also mock out the entire server when doing unit tests.
For the MockTransport, I simply return canned json data from static .js files in the format that the widget expects.