can
Version:
MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.
742 lines (500 loc) • 23.6 kB
HTML
<!--####################################################################
THIS IS A GENERATED FILE -- ANY CHANGES MADE WILL BE OVERWRITTEN
INSTEAD CHANGE:
source: [object Object]
@module can-fixture-socket
######################################################################## -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>CanJS - can-fixture-socket</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" type="text/css" href="./static/bundles/bit-docs-site/static.css">
<link rel="shortcut icon" sizes="16x16 24x24 32x32 48x48 64x64" href="/docs/images/canjs_favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="../docs/images/canjs_favicon_57x57.png">
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="../docs/images/canjs_favicon_57x57.png">
<link rel="apple-touch-icon" sizes="72x72" href="../docs/images/canjs_favicon_72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../docs/images/canjs_favicon_114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="../docs/images/canjs_favicon_128x128.png">
<link rel="apple-touch-icon" sizes="144x144" href="../docs/images/canjs_favicon_144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="../docs/images/canjs_favicon_152x152.png">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta name="apple-mobile-web-app-status-bar-style" content="white-translucent">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-2302003-11', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger"/>
<label for="nav-trigger">Menu</label>
<div id="everything">
<div id="left" class="column">
<div class="top-left">
<div class="brand">
<div class="logo">
<a href="../index.html" alt="CanJS"></a>
<div class="dropdown project-dropdown">
<a href="https://donejs.com/">DoneJS</a>
<a href="http://stealjs.com/">StealJS</a>
<a href="http://jquerypp.com/">jQuery ++</a>
<a href="https://funcunit.com/">FuncUnit</a>
<a href="http://documentjs.com/">DocumentJS</a>
</div>
</div>
<div class="version">
<div class="version-number">
3.0.0
</div>
<div class="dropdown version-dropdown">
<a href="https://v2.canjs.com">2.3.27</a>
</div>
</div>
</div>
<div class="search-bar">
<p>
</p>
</div>
</div>
<div class="bottom-left">
<div class="social-side-container">
<ul class="social-side">
<li>
<a class="header-mobile github" href="https://github.com/canjs/canjs" target="_blank"><img class="social-icon-small" src="../docs/images/github.png">Github</a>
</li>
<li>
<a class="header-mobile twitter" href="https://twitter.com/canjs" target="_blank"><img class="social-icon-small" src="../docs/images/twitter.png">Twitter</a>
</li>
</ul>
<ul class="social-side">
<li>
<a class="header-mobile" href="https://gitter.im/canjs/canjs" target="_blank">Chat</a>
</li>
<li>
<a class="header-mobile" href="http://forums.donejs.com/c/canjs" target="_blank">Forum</a>
</li>
</ul>
</div>
<ul>
<li class="
">
<a class="page"
href="guides.html"
title="Welcome to CanJS! These guides are here to help you develop and improve your relationship with CanJS. After all, picking a JavaScript framework is a commitment. We want CanJS to be the
framework you marry. This page helps you know how advance through the different stages of this
relationship:">
Guides
</a>
</li>
<li class="
">
<a class="page"
href="can-core.html"
title="The best, most hardened and generally useful libraries in CanJS.">
Core
</a>
</li>
<li class="
parent
expanded">
<a class="page"
href="can-ecosystem.html"
title="Useful libraries that extend or add important features to the core collection.">
Ecosystem
</a>
<ul>
<li class="
">
<a class="module"
href="can-construct-super.html"
title="can.Construct.super is a plugin that makes it easier to call base
functions from inside inheriting functions.">
can-construct-super
</a>
</li>
<li class="
">
<a class="module"
href="can-define-stream.html"
title="Define property values using streams. can-stream is used internally
to provide the stream functionality.">
can-define-stream
</a>
</li>
<li class="
">
<a class="module"
href="can-fixture.html"
title="can-fixture intercepts an AJAX request and simulates the response with a file or function.">
can-fixture
</a>
</li>
<li class="current
parent
expanded">
<a class="module"
href="can-fixture-socket.html"
title="Simulate socket.io services.">
can-fixture-socket
</a>
<ul>
<li>
<span>types</span>
<ul>
<li class="
">
<a class="typedef"
href="can-fixture-socket.socket-event-listener.html"
title="A listener handler that will be executed to handle the socket event.">
SocketEventListener
</a>
</li>
</ul>
</li>
<li>
<span>properties</span>
<ul>
<li class="
">
<a class="constructor"
href="can-fixture-socket.Server.html"
title="Intercept socket.io messages and simulates socket.io server responses.">
Server
</a>
</li>
<li class="
">
<a class="function"
href="can-fixture-socket.requestHandlerToListener.html"
title="Transforms XHR request handler into socket event listener.">
requestHandlerToListener
</a>
</li>
<li class="
">
<a class="function"
href="can-fixture-socket.storeToListeners.html"
title="Returns a set of listeners transformed from fixture store request handlers. Useful for working with REST-ful resources.">
storeToListeners
</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="
">
<a class="module"
href="can-jquery.html"
title="Extensions to the event system so that can events and jQuery events are cross-bound.
Importing can-jquery will return the jQuery object and wire up the event system.
var $ = require("can-jquery");
var div = $("<div>");
div.on("inserted", function(){
// it inserted!
});
$("body").append(div);">
can-jquery
</a>
</li>
<li class="
">
<a class="module"
href="can-stache-converters.html"
title="Provides a set of converters useful for two-way binding with form elements such as <input> and <select>.">
can-stache-converters
</a>
</li>
<li class="
">
<a class="module"
href="can-stream.html"
title="Convert observable values into streams. Kefir is used internally to provide the stream functionality.">
can-stream
</a>
</li>
<li class="
">
<a class="module"
href="can-vdom.html"
title="A browser-lite environment for Node.js or a worker thread.">
can-vdom
</a>
</li>
<li class="
">
<a class="module"
href="can-view-import.html"
title="">
can-view-import
</a>
</li>
<li class="
">
<a class="module"
href="can-zone.html"
title="">
can-zone
</a>
</li>
<li class="
">
<a class="module"
href="steal-stache.html"
title="A StealJS extension that allows stache templates as dependencies.">
steal-stache
</a>
</li>
</ul>
</li>
<li class="
">
<a class="page"
href="can-infrastructure.html"
title="Utility libraries that power the core and ecosystem collection.">
Infrastructure
</a>
</li>
<li class="
">
<a class="page"
href="can-legacy.html"
title="Former libraries that we still accept patches for, but are not under active development.">
Legacy
</a>
</li>
</ul>
</div>
</div>
<div id="right" class="column">
<div class="top-right">
<div class="top-right-top">
<ul class="top-right-bitovi">
<li class="dropdown">
<a href="http://bitovi.com" class="bitovi icon-bits">Bitovi</a>
<ul class="dropdown-menu">
<li><a href="http://bitovi.com">Bitovi.com</a></li>
<li><a href="http://bitovi.com/blog/">Blog</a></li>
<li><a href="http://bitovi.com/consulting/">Consulting</a></li>
<li><a href="http://bitovi.com/training/">Training</a></li>
<li><a href="http://bitovi.com/open-source/">Open Source</a></li>
</ul>
</li>
</ul>
<div class="brand">
<div class="logo">
<a href="../index.html" alt="CanJS"></a>
</div>
</div>
<ul class="top-right-links">
<li>
<a href="https://gitter.im/canjs/canjs">Chat</a>
</li>
<li>
<a href="http://forums.donejs.com/c/canjs">Forum</a>
</li>
<li>
<a class="github-button nav-social" href="https://github.com/canjs/canjs" data-count-href="/canjs/canjs/stargazers" data-count-api="/repos/canjs/canjs#stargazers_count">Star</a>
</li>
<li>
<a href="https://twitter.com/canjs" class="twitter-follow-button nav-social" data-show-count="true" data-show-screen-name="false">Follow @canjs</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</li>
</ul>
</div>
<div class="breadcrumb">
<li><a href="../index.html">CanJS</a></li> /
<li><a href="can-ecosystem.html">Ecosystem</a></li> /
<li><a href="can-fixture-socket.html">can-fixture-socket</a></li>
<li class="breadcrumb-dropdown">/ <a> On this page</a>
<ul class="on-this-page"></ul>
</li>
<div class="nav-toggle" title="Back to top"></div>
</div>
</div>
<div class="bottom-right">
<article>
<section class="title">
<div class="page-type">
<h1>can-fixture-socket</h1>
<div>module</div>
</div>
<section class="description">
<p>Simulate socket.io services.</p>
</section>
</section>
<section class="on-this-page-table">
</section>
<section class="title-footer">
<ul class="title-links">
<!-- <li><a href="#">docco</a></li> -->
<li><a href="//github.com/canjs/canjs/tree/v3.0.0/node_modules/can-fixture-socket/can-fixture-socket.md">source</a></li>
<!-- <li><a href="#">download</a></li> -->
<!-- <li><a href="#">tests</a></li> -->
</ul>
</section>
<div class="signature">
<h2 class="signature-title">
<code>Object</code>
</h2>
<p><code>can-fixture-socket</code> intercepts socket.io messages and simulates socket.io server responses.</p>
<p>The <code>can-fixture-socket</code> module exports an object with:</p>
<ul>
<li><a href="can-fixture-socket.Server.html" title="Intercept socket.io messages and simulates socket.io server responses.">Server</a>, a constructor function which instance intercepts the socket.io connection;</li>
<li><a href="can-fixture-socket.requestHandlerToListener.html" title="Transforms XHR request handler into socket event listener.">requestHandlerToListener</a>, a helper to convert XHR request handler into <a href="can-fixture-socket.socket-event-listener.html" title="A listener handler that will be executed to handle the socket event.">SocketEventListener</a>;</li>
<li><a href="can-fixture-socket.storeToListeners.html" title="Returns a set of listeners transformed from fixture store request handlers. Useful for working with REST-ful resources.">storeToListeners</a>, a helper to convert all <a href="can-fixture/StoreType.html" title="">Store</a> request handlers into <a href="can-fixture-socket.socket-event-listener.html" title="A listener handler that will be executed to handle the socket event.">SocketEventListener</a>.</li>
</ul>
<p>With three simple steps you can test your real-time application that uses socket.io:</p>
<ol>
<li>create a mock server that intercepts socket.io;</li>
<li>mock server behavior;</li>
<li>test your application.</li>
</ol>
<pre><code class="language-js">var fixtureSocket = require("can-fixture-socket");
// Import socket-io client:
var io = require("socket.io-client");
// Create a mock server that intercepts socket.io:
var mockServer = new fixtureSocket.Server(io);
// Mock server behavior
mockServer.on("connection", function(){
mockServer.emit("notifications", {test: "OK"})
});
// Client. Create socket.io connection:
var socket = io("http://localhost:8080/api");
// Test your application:
socket.on("connect", function(){
assert.ok(true, "socket connected");
});
socket.on("notifications", function(data){
assert.deepEqual(data, {test: "OK"}, "received notifications message");
});
</code></pre>
</div>
<section class="body">
<h2>Use basics</h2>
<p>Lets say we wanted to test a simple app that connects to <code>socket.io</code>, and
once connected, creates a message, and logs when the message is created.</p>
<p>That app could look like the following:</p>
<pre><code class="language-js">var socket = io();
socket.on("connect", function(){
socket.emit("messages create", {text: "A new message"});
});
socket.on("message created", function(data){
// data.text === "A new message"
console.log("Server sent out a new message we just created", data);
});
</code></pre>
<p>To test this, we'll first use <a href="can-fixture-socket.Server.html" title="Intercept socket.io messages and simulates socket.io server responses.">can-fixture-socket.Server</a> to intercept the socket connection:</p>
<pre><code class="language-js">var io = require("socket.io-client");
var fixtureSocket = require("can-fixture-socket");
var mockServer = new fixtureSocket.Server(io);
</code></pre>
<p>Now we can mock the socket server by creating socket event listeners and emitting socket events:</p>
<pre><code class="language-js">mockServer.on("messages create", function(data){
console.log("New message received", data);
mockServer.emit("message created", data);
});
</code></pre>
<p>To see this in action:</p>
<div class='demo_wrapper' data-demo-src='demos/can-fixture-socket/basic-app.html'></div>
<h3>Acknowledgement callbacks</h3>
<p>We also can use socket.io <a href="http://socket.io/docs/#sending-and-getting-data-(acknowledgements)">acknowledgement callbacks</a>:</p>
<pre><code class="language-js">mockServer.on("users create", function(user, ackCb){
console.log("Simulating saving a new user to DB and return the new user id", user);
ackCB({
id: Math.random()
});
});
</code></pre>
<p>Client code:</p>
<pre><code class="language-js">var socket = io();
socket.on("connect", function(){
socket.emit("users create", {name: "Ilya", likes: "skiing"}, function (data) {
// data is what server calls the acknowledgement callback
// with (e.g. data.id is the new user id).
console.log(data.id);
});
});
</code></pre>
<h2>Use with can-fixture.Store</h2>
<p>With can-fixture <a href="can-fixture.store.html" title="">store</a> we can create a store of items and emulate a fully working CRUD service. Optionally, we can use <a href="can-set.Algebra.html" title="Perform set logic with an awareness of how certain properties represent a set.">Algebra</a> to power our store filtering, pagination, and sorting abilities.</p>
<pre><code class="language-js">// Import can-fixture that provides `store` method for creating a store:
var fixture = require("can-fixture");
var canSet = require("can-set");
// Create a fixture store:
var messagesStore = fixture.store([
{id: 1, title: "One"},
{id: 2, title: "Two"},
{id: 3, title: "Three"}
], new canSet.Algebra({}));
</code></pre>
<p>We can mock the socket.io connection with the rich behavior of <em>fixture stores</em> using the <a href="can-fixture-socket.requestHandlerToListener.html" title="Transforms XHR request handler into socket event listener.">requestHandlerToListener</a> helper. <code>requestHandlerToListener</code>
converts a <em>fixture store request handler</em> to a <em>socket.io event listener</em>.</p>
<pre><code class="language-js">var fixtureSocket = require("can-fixture-socket");
var io = require("socket.io-client");
var mockServer = new fixtureSocket.Server(io);
mockServer.on("messages get", fixtureSocket.requestHandlerToListener( messagesStore.getData ));
</code></pre>
<p>Or we can use <a href="can-fixture-socket.storeToListeners.html" title="Returns a set of listeners transformed from fixture store request handlers. Useful for working with REST-ful resources.">storeToListeners</a> helper to convert all CRUD <em>fixture store request handlers</em> into <em>socket.io event listeners</em>:</p>
<pre><code class="language-js">var listeners = fixtureSocket.storeToListeners( messagesStore );
mockServer.on({
"messages remove": listeners.destroyData,
"messages create": listeners.createData,
"messages update": listeners.updateData
});
</code></pre>
<h2>Use with FeathersJS</h2>
<p><a href="http://feathersjs.com/">Feathers</a> is a minimalist, service-oriented, real-time web framework for modern applications. It is a NodeJS framework built on top of Express. It allows you to build REST-ful services and works with three <a href="https://docs.feathersjs.com/providers/">providers</a>: standard HTTP communication, WebSockets and Primus.</p>
<p>The mocked server exposes [can-fixture-socket.Server.prototype.onFeathers] method to simulate <a href="http://feathersjs.com/">FeathersJS</a> CRUD services.</p>
<p>For example, given the following FeathersJS client app:</p>
<pre><code class="language-js">var socket = io("http://api.my-feathers-server.com");
var app = feathers()
.configure(hooks())
.configure(feathersSocketio(socket));
// Create FeathersJS CRUD service for "messages" resource:
var messagesService = app.service("messages");
</code></pre>
<p>We can simulate it with a <a href="can-fixture.store.html" title="">store</a> as follows:</p>
<pre><code class="language-js">var messagesStore = fixture.store([
{id: 1, title: "One"},
{id: 2, title: "Two"},
{id: 3, title: "Three"}
], new canSet.Algebra({}));
mockServer.onFeathersService("messages", fixtureStore);
</code></pre>
<p>Now you can test your FeathersJS app:</p>
<pre><code class="language-js">messagesService.find({}).then(function(data){
assert.equal(data.total, 3, "find should receive 3 items");
});
messagesService.get(1).then(function(data){
assert.deepEqual(data, {id: 1, title: "One"}, "get should receive an item");
});
messagesService.create({title: "Four"}).then(function(data){
assert.equal(data.title, "Four", "create should add an new item");
});
</code></pre>
</section>
<script type="text/javascript">
var docObject = {"src":{"path":"node_modules/can-fixture-socket/can-fixture-socket.md"},"description":"Simulate socket.io services. \n\n\n","type":"module","title":"","types":[{"type":"Object","options":[],"description":"\n\n`can-fixture-socket` intercepts socket.io messages and simulates socket.io server responses.\n\nThe `can-fixture-socket` module exports an object with:\n\n- [can-fixture-socket.Server], a constructor function which instance intercepts the socket.io connection;\n- [can-fixture-socket.requestHandlerToListener], a helper to convert XHR request handler into [can-fixture-socket.socket-event-listener];\n- [can-fixture-socket.storeToListeners], a helper to convert all [can-fixture/StoreType] request handlers into [can-fixture-socket.socket-event-listener].\n\nWith three simple steps you can test your real-time application that uses socket.io:\n\n 1. create a mock server that intercepts socket.io;\n 2. mock server behavior;\n 3. test your application.\n\n```js\nvar fixtureSocket = require(\"can-fixture-socket\");\n\n// Import socket-io client:\nvar io = require(\"socket.io-client\");\n\n// Create a mock server that intercepts socket.io:\nvar mockServer = new fixtureSocket.Server(io);\n\n// Mock server behavior\nmockServer.on(\"connection\", function(){\n mockServer.emit(\"notifications\", {test: \"OK\"})\n});\n\n// Client. Create socket.io connection:\nvar socket = io(\"http://localhost:8080/api\");\n\n// Test your application:\nsocket.on(\"connect\", function(){\n assert.ok(true, \"socket connected\");\n});\n\nsocket.on(\"notifications\", function(data){\n assert.deepEqual(data, {test: \"OK\"}, \"received notifications message\");\n});\n```\n"}],"name":"can-fixture-socket","parent":"can-ecosystem","comment":" ","pathToRoot":".."};
</script>
</article>
<footer><p>CanJS is part of <a href="http://donejs.com" target="_blank">DoneJS</a>. Created and maintained by the core <a href="https://donejs.com/About.html#section=section_Team" target="_blank">DoneJS team</a> and <a href="http://bitovi.com" target="_blank">Bitovi</a>. <strong>Currently 3.0.0.</strong></p></footer>
</div>
</div>
</div>
<script>
steal = {
instantiated: {
"bundles/bit-docs-site/static.css!$css" : null
}
};
</script>
<script type='text/javascript' data-main="bit-docs-site/static" src="./static/node_modules/steal/steal.production.js"></script>
<script async defer src="https://buttons.github.io/buttons.js"></script>
</body>
</html>