In software development, sometimes we aren’t sure how to solve a problem. It may happen when you are using a new API, framework, or just because you never had a similar problem before.

Using TDD in this scenario is hard. In order to write the test first, you need to be able to define the expectations, if you don’t know that, TDD is gonna be really challenging.

In Agile Development there’s a technique for this situation called Spike. This term comes from Extreme Programming, where “A spike solution is a very simple program to explore potential solutions”.

To implement a spike solution, you normally create a small program very quickly testing the problem in question. When you have the answers that you need, you go back and build it again, but this time using TDD.

I got very excited when I discover Spikes, because I have been doing it for a while, and I really didn’t know that it had a name.

What about you, have you been writing spike solutions?

You can get more information about it here:

http://www.jamesshore.com/Agile-Book/spike_solutions.html

That’s it for today! See you soon

In the last week, I had a problem after including some new libraries in the project that I was working on. There was no exception occurring, but the Web Sockets stopped to work.

Unfortunately, we just realized the problem after some days. This gave me some hours of work (and some gray hairs), trying to figure out manually what commit breaks the web socket. Actually, it was my mistake, I didn’t write any integration test for the Web Socket.

After discovering the problem. (an integration problem with the lib spring-cloud-sleuth), I decided to write a test for it. I don’t want to have the same problem again!

I had never written tests for Web Sockets before, and I didn’t find any clear and good example for it. Then, I decided to share my solution here, maybe it will help someone that needs it.

This is the websocket configuration using Spring:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
                .addEndpoint("/websocket")
                .setAllowedOrigins("*")
                .withSockJS();
    }
}s

And here I put the test using Stomp Client. Basically, the test connects to the Web Socket, then subscribes to the topic and sends a message. I used the class BlockingQueue, in order to wait for the asynchronous response.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebIntegrationTest
public class WebSocketTest {

    static final String WEBSOCKET_URI = "ws://localhost:8080/websocket";
    static final String WEBSOCKET_TOPIC = "/topic";

    BlockingQueue<String> blockingQueue;
    WebSocketStompClient stompClient;

    @Before
    public void setup() {
        blockingQueue = new LinkedBlockingDeque<>();
        stompClient = new WebSocketStompClient(new SockJsClient(
                asList(new WebSocketTransport(new StandardWebSocketClient()))));
    }

    @Test
    public void shouldReceiveAMessageFromTheServer() throws Exception {
        StompSession session = stompClient
                .connect(WEBSOCKET_URI, new StompSessionHandlerAdapter() {})
                .get(1, SECONDS);
        session.subscribe(WEBSOCKET_TOPIC, new DefaultStompFrameHandler());

        String message = "MESSAGE TEST";
        session.send(WEBSOCKET_TOPIC, message.getBytes());

        Assert.assertEquals(message, blockingQueue.poll(1, SECONDS));
    }

    class DefaultStompFrameHandler implements StompFrameHandler {
        @Override
        public Type getPayloadType(StompHeaders stompHeaders) {
            return byte[].class;
        }

        @Override
        public void handleFrame(StompHeaders stompHeaders, Object o) {
            blockingQueue.offer(new String((byte[]) o));
        }
    }
}

Lesson learned

Always write integration tests. It can prevent bugs when you upgrade libraries, or when you include new ones. It also can save some hours and headaches in the future.

If you want, you can clone the complete project from my github:

https://github.com/rafaelhz/testing-spring-websocket.git

If you have some doubts, or have some suggestion to improve this code, please let me know.

That’s it for today friends, until next time!

Webpack is a powerful tool for bundling modules, helping you to organize your code, bundling it in a single js file.

Today, I’m going to create a simple project with webpack. My goal here is to show how to organize Js modules using this tool. Let’s get to it!

Installation

First, let’s install webpack globally. (You also need Node and Npm installed).

npm install webpack -g

Project structure

This is the folder structure of our project:

/webpack-example
  /app.js
  /module1.js
  /module2.js  
  /index.html  
  /webpack.config.js

app.js

The app file requires the module1 and module2.

var module1 = require("./module1.js");
var module2 = require("./module2.js");

document.write('<p>' + module1() + '</p>');
document.write('<p>' + module2() + '</p>');

module1.js

module.exports = function() {
    return 'this is the module 1';
}

module2.js

module.exports = function() {
    return 'this is the module 2';
}

index.html

In the index.html, we just include the bundle.js file. Webpack will compile the modules in this file.

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h1>Webpack project</h1>
        <script type="text/javascript" src="bundle.js" charset="utf-8"></script>
    </body>
</html>

webpack.config.js

This is the webpack configuration. Basically, we are saying to webpack where our entry file is and the bundle filename.

var webpack = require("webpack");
module.exports = {
    entry: "./app.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
};

Compiling

Now we can run webpack:

webpack

It will compile our modules and create a bundle.js file. Open the index.html file in your browser to see the result.

Development Server

In order to serve the static files compiled by webpack, we can use the webpack-dev-server. It automatically updates the browser page when a bundle is recompiled.

Let’s install it:

npm install webpack-dev-server -g

Now we just run:

webpack-dev-server 

Now open: http://localhost:8080/ to see the result.

External Modules

Let’s say that we need a external module in our project, Jquery for example.

First, let’s install jquery using npm:

npm install jquery

Then we just import and use!

var module1 = require("./module1.js");
var module2 = require("./module2.js");
var jquery = require("jquery");

jquery('body').append('<p>Jquery works!</p>');

Conclusion

You could see how is easy to organize a project in modules using webpack. This is just a simple example, we can do a lot of other things with this tool, like uglyfy, minify, compress static assets, etc.

In the next post, we will use Webpack with Angular2, and build a web application!

You can learn more about webpack here: https://webpack.github.io/

That’s it for today!

I hope you enjoyed! Until next time!

I have been using the Lodash library a lot lately, then I decided to list here some functions that I consider very useful. You will notice how it can simplify your code, making it more elegant, cleaner, and functional.

Lodash, is a tool kit of JS functions that provides methods for manipulating objects and collections. It’s like a utility belt!

Filtering

In order to filter collections, we can use the filter method. It’s returns only those objects that contain the specified key, and it’s also supports nested objects.

let pets = [
  {name: 'Snoopy',   likes: [{toy: 'ball'}]},
  {name: 'Meow',     likes: [{food: 'milk'}]},
  {name: 'Garfield', likes: [{food: 'milk'}, {food: 'lasagna'}]}
];
_.filter(pets, {likes: [{food: 'milk'}]});
 
//returns [{name: 'Meow', likes: [...]}, {name: 'Garfield', likes: [..., ...]}]

Grouping objects

The groupBy method takes an array of objects and groups them by some field or condition.

let pets = [
  {name: 'Snoopy',   type: 'dog']},
  {name: 'Meow',     type: 'cat'}]},
  {name: 'Garfield', type: 'cat'}]}
];

_.groupBy(pets, 'type');

//returns {dog: [{name: 'Snoopy',...}],
//         cat: [{name: 'Meow', ...}, {name: 'Garfield', ...}]}

Merging Objects

The merge method takes multiple source objects, and merges their properties together into an object.

let obj1 = {id: 1, tag: 'js', values: [1, 2]};
let obj2 = {name: 'John'};
let obj3 = {id: 2, tag: null, values: [3, 4]};

_.merge(obj1, obj2, obj3);

//returns {id: 2, tag: null, values: [3, 4], name: 'John'}

Selecting properties to create a new object

The pick method creates an object composed of the picked object properties.

let pet = {name: 'Meow', type: 'cat', color: 'white'};

_.pick(pet, ['name', 'color'])

//returns {name: 'Meow', color: 'white'}

Chaining

Lodash allows us to chain the collection functions instead of using a bunch of temporary variables, making your code more readable.

Let’s say that we have an array of pets and we need:

  1. get all pets that are dogs
  2. get just the dog name
  3. order by name
  4. join the names with commas
let pets = [
  {name: 'Goofy', type: 'dog'},
  {name: 'Snoopy', type: 'dog'},
  {name: 'Dino', type: 'dog'},
  {name: 'Garfield', type: 'cat'},
];

_.chain(pets)
 .filter({type: 'dog'})
 .map('name')
 .sort()
 .join(',')
 .value();

//returns  Dino,Goofy,Snoopy'

More about Lodash

There are hundreds of useful functions available in the Lodash library. Here I just listed some simple examples, but they’re enough to realize how useful it can be for your Js projects.

If you want to learn more, Lodash website is an excellent resource. Feel free to write your questions in the comment box.

Thanks for reading. Until next time!

Testing dates in unit tests is not always an easy stuff, In this post, I’m going to show an easy and elegant way to do that in JS using Jasmine.

First, take a look at the function below. It’s calculating the difference between today and a date passed by param. To make the example easier, I’m using momentJS library to work with dates.

function getDaysBetweenTodayAndADate(date) {
  let today = moment();
  return date.diff(today, 'days'); 
}

How can we test it? The moment object will always return the current date, how can we write a test that can pass every day?

In order to solve this problem, we can use Jasmine Clock to mock the current date.

describe('testing dates in js', function () {

  beforeEach(() => {
    let today = moment('2016-01-01').toDate();
    jasmine.clock().mockDate(today);
  });

  it('should return the difference between today', () => {
    let date = moment('2016-01-05');
    expect(4).toEqual(getDaysBetweenTodayAndADate(date));
  });

});

If you are using Jasmine as your test tool, it’s an easy way to mock dates!

However, if you are not using Jasmine, there is another way to solve this problem, you can create a date utility class and mock it. I usually do it using Java for example, but it’s a topic for another day.

I hope you enjoyed this post!

Until next time!