I have a function in controller:
function get(request) {
return UserService.get({
id: request.id,
transformResponse: function(data) {
return angular.fromJson(data);
}
});
};
And test like this:
var $scope;
var controller;
var UserService;
beforeEach(function() {
angular.mock.module(function($provide) {
UserService = jasmine.createSpyObj('UserService', ['get']);
$provide.value('UserService', UserService);
});
});
beforeEach(inject(function($rootScope, $controller, UserService) {
$scope = $rootScope.$new();
controller = $controller('...' {
$scope: $scope,
UserService: UserService
});
$scope.$digest();
}));
it('should call user service get function when getting user', function() {
var request = { id: 5 };
controller.get(request);
expect(UserService.get).toHaveBeenCalledWith(request);
});
Test passed, but karma coverage display that function transformResponse not covered by the test.
How I must correctly mock this function? Thanks!
Related
I'm having difficulty passing the value from my personal js to the controller and recovering it on the personal tpl page.
This module will serve to customize product after some selections and fields to fill out.
The selections pass from tabs to tabs.
The problem is that I can't get the value {$ var}
I have:
JS in root->modules->modulename->views->js->namejsfile.js
CONTROLLER in root->modules->modulename->controllers->front->controllername.php
VIEW in root->modules->modulename->views->templates->front->filename.tpl
in JS
$('#send').click(function(){
var ciao = 'cioaa';
var myUrl = prestashop.urls.base_url + 'index.php?fc=module&module=configuratore';
$.ajax({
type: 'get',
cache:false,
url: myUrl,
data: {
ajax: true,
datas:ciao,
action: 'fromAjax',
},
})
.done(function() {
console.log('Success!');
})
.fail(function() {
console.log('error');
});
});
in PHP
class ConfiguratoreTaskModuleFrontController extends ModuleFrontController
{
public function __construct()
{
parent::__construct();
}
public function init()
{
parent::init();
}
public function initContent()
{
parent::initContent();
$this->setTemplate('module:configuratore/views/templates/front/task.tpl');
}
$this->fromAjax();
}
public function fromAjax()
{
$mVar = Tools::getValue('datas');
return $this->context->smarty->assign(array('var'=>$mVar));
}
in TPL
{$var}
<?
public function fromAjax()
{
$mVar = Tools::getValue('datas');
$this->context->smarty->assign(array('var'=>$mVar));
$templateFile = 'module:configuratore/views/templates/front/task.tpl';
$html = $this->fetch($templateFile);
die($html); // pass to JS
}
in JS:
.done(function(html) {
console.log(html);
})
I am trying to consume rest api in ReactJS. But it's showing undefined.
Here is my code..
ReactJS code:
<script type="text/jsx">
var JavaEEWSTest = React.createClass({
getInitialState: function () {
return {text: ''};
},
componentDidMount: function(){
$.ajax({
url: "http://localhost:8080/hi"
}).then(function(data) {
this.setState({text: data.text});
alert(data.text);
}.bind(this))
},
render: function() {
return <div>Response - {this.state.text}</div>;
}
});
React.render(<JavaEEWSTest />, document.getElementById('component'));
</script>
Here is my Spring boot code:
#RestController
#CrossOrigin(origins = "http://localhost:3000")
public class HelloController {
#RequestMapping(value="/hi",method=RequestMethod.GET)
public String sayHello()
{
return "hello";
}
}
While making AJAX calls, we can use axios-react, the quick link: https://www.npmjs.com/package/axios
And instead of the function keyword in your code, you may use the ES6 version's =>.
Below is an example of getting the response from the rest API.
constructor() {
super();
this.state = {
data : []
}
}
componentDidMount() {
axios.get(URL)
.then((res) => {
this.setState({data:res.data});
console.log(this.state.data);
})
.catch((error) => {
console.log(error);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
I have converted my fetch calls to use breeze.EntityQuery but how can I write my unit tests to mock the breeze client? Here is my code for the unit test fetch call that I'm trying to write for breeze.
class HttpStub {
fetch(url) {
var response = this.itemStub;
this.url = url;
return new Promise((resolve) => {
resolve({ json: () => response });
});
}
configure(func) {}
}
describe('Order', () => {
var sut, http, itemStubs, itemFake;
beforeEach(() => {
http = new HttpStub();
sut = new Order(http);
itemStubs = [1];
itemFake = [2];
http.itemStub = itemStubs;
});
describe('getOrders', () => {
it('should return orders', (done) => {
var info = new Info("1", "C", null, null);
sut.getOrders(info).then(result => {
expect(result).toBe(itemStubs);
expect(result).not.toBe(itemFake);
done();
});
});
});
});
Try using the jasmine spyOn function with callFake. Jasmine's spies are an easier way to mock a function call.
beforeEach(function () {
spyOn(httpClient, "fetch").and.callFake(function () {
return new Promise(function (resolve, reject) {
var fetchResponse = "the fake response";
resolve(fetchResponse);
});
});
});
An example (with TypeScript)
import { HttpClient } from "aurelia-fetch-client";
import { autoinject, Container } from "aurelia-framework";
#autoinject
export class DemoClass {
constructor(private httpClient: HttpClient) { }
public UseTheHttpClient() {
return this.httpClient.fetch("some_url");
}
}
describe("the demo class", function () {
let container: Container = new Container();
let httpClient: HttpClient = new HttpClient(); // create an http client
container.registerInstance(HttpClient, httpClient);
let demoClass: DemoClass = container.get(DemoClass);
beforeEach(function () { // spy on that HTTP client
spyOn(httpClient, "fetch").and.callFake(function () {
return new Promise(function (resolve, reject) {
resolve("some_fake_response");
});
});
});
it("returns the fake response", function (done) {
demoClass.UseTheHttpClient().then((response) => {
expect(response).toBe("some_fake_response");
done();
});
});
});
I'm using jasmine+karma to run the following code...
and get the following error:
Expected { then : Function, catch : Function, finally : Function } to equal 123.
Can someone help me understand why I don't get a resolved value for my promise. thanks
'use strict';
angular
.module('example', ['ui.router'])
.config(function($stateProvider) {
$stateProvider
.state('stateOne', {
url: '/stateOne',
resolve: {cb: function($q) {
var deferred = $q.defer();
deferred.resolve(123);
return deferred.promise;
}},
controller: function($scope, cb) {console.log(' * in controller', cb);},
templateUrl: 'stateOne.html'
});
})
.run(function($templateCache) {
$templateCache.put('stateOne.html', 'This is the content of the template');
});
describe('main tests', function() {
beforeEach(function() {module('example');});
describe('basic test', function($rootScope) {
it('stateOne', inject(function($rootScope, $state, $injector, $compile) {
var config = $state.get('stateOne');
expect(config.url).toEqual('/stateOne');
$compile('<div ui-view/>')($rootScope);
$rootScope.$digest();
expect($injector.invoke(config.resolve.cb)).toEqual(123);
}));
});
});
Ok, Figured it out with some help (via email) from Nikas, whose blog I found at:
http://nikas.praninskas.com/angular/2014/09/27/unit-testing-ui-router-configuration/.
Here is a succinct example that demonstrates how to test the resolve values in ui.router, where the values involve $http.
angular
.module('example', ['ui.router'])
.factory('Clipboard', function($http) {
return {
get: function(args) {
return $http.get('/db/clipboard');
}
};
})
.config(function($stateProvider) {
$stateProvider
.state('stateOne', {
resolve: {cb: function(Clipboard) {
return Clipboard.get();
}}
});
});
describe('main tests', function() {
beforeEach(function() {module('example');});
it('stateOne', inject(function($state, $injector, $httpBackend) {
$httpBackend.whenGET('/db/clipboard').respond({a:1});
$injector.invoke($state.get('stateOne').resolve['cb'])
.then(function(res) {console.log(' *res ', res.data);})
.catch(function(err) {console.log(' *err ', err);});
$httpBackend.flush();
}));
afterEach(inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
});
As I want to implement a chat in AngularJS, I want to use the promise/deferred principle. My ChatService looks like the following:
factory('ChatService', ['$q', '$resource', function($q, $resource) {
var Service = {};
var connected = false;
var connection;
var chatResource = $resource('/guitars/chat/:action', {action: '#action'}, {
requestChatroomId: {
params: {
action: 'requestChatroomId'
},
method: 'GET'
},
sendMessage: {
params: {
action: 'sendMessage'
},
method: 'POST'
}
});
Service.connect = function(cb) {
var deferred = $q.defer();
chatResource.requestChatroomId(function(data) {
connection = new WebSocket('ws://127.0.0.1:8888/realtime/' + data.chatroomId);
connection.onerror = function (error) {
deferred.reject('Error: ' + error);
};
connection.onmessage = function (e) {
cb.call(this, e.data);
deferred.notify(e.data);
};
connected = true;
});
return deferred.promise;
};
Service.sendMessage = function(msg) {
if(!connected) {
return;
}
chatResource.sendMessage({message: msg});
}
return Service;
}])
My controller using the ChatService is:
app.controller('ChatCtrl', ['$scope', 'ChatService', function($scope, ChatService) {
$scope.chat = {};
$scope.chat.conversation = [];
var $messages = ChatService.connect(function(message) {
$scope.$apply(function() {
// #1 THIS FIRES EVERY TIME
$scope.chat.conversation.push(message);
});
});
$messages.then(function(message) {
console.log('Finishes - should never occur!')
}, function(error) {
console.log('An error occurred!')
}, function(message) {
// #2 THIS FIRES ONLY IF THERE IS AN INTERACTION WITH THE ANGULAR MODEL
console.log(message);
});
$scope.sendMessage = function(event) {
ChatService.sendMessage($scope.chat.message);
$scope.chat.message = '';
};
}]);
If something is pushed from the server, callback #1 is called, but callback #2 wont be called until there is some interaction with the angular-model, i.e. start writing something in the input-Box. What is the reason for that behaviour?
Okay the reason was, that AngularJS was not aware of a change. So I injected the $rootScope to my ChatService:
factory('ChatService', ['$q', '$resource', '$rootScope', function($q, $resource, $rootScope) {
and in connection.onmessage I called $apply() on $rootScope:
connection.onmessage = function (e) {
deferred.notify(e.data);
$rootScope.$apply();
};