Assert module use in nodejs? - javascript

Hello everyone I was reading node official documentation, and I've seen the "Assert" module, but don't understand its use, my conclutions up to now are that is like the (try--catch) of some languages, the examples on official documentation are not enough for me to understand the module, could you guys help me please?

These would be used for unit testing.
This module is used for writing unit tests for your applications, you can access it with require('assert').
http://nodejs.org/api/assert.html
The goal of a unit test is to test individual units of your code.
For example, to test a function, you give it the input and know what output to expect. This will isolate that function so you can be sure there is not an error in other parts of your code.

From the Node assert documentation:
The assert module provides a simple set of assertion tests that can be used to test invariants. The module is intended for internal use by Node.js, but can be used in application code via require('assert'). However, assert is not a testing framework, and is not intended to be used as a general purpose assertion library.
A simple use of the assert module would be to prevent a division by zero:
var noDivZero = (dividend, divisor) => {
try {
assert(divisor !== 0, 'DivisionByZeroException')
return dividend / divisor
} catch(e) {
return e.message
}
}
noDivZero(10, 0); // DivisionByZeroException

Related

JavaScript unittesting with Jest - how do I run my scripts in the browser?

I use Jest to unittest my JavaScript code. Or at least I'd really want to use Jest.
The problem is that Jest need me to use module.exports in order to use the function inside of the testfile. And that means I can't use my JavaScript in the browser.
The simple Jest test looks like this:
// divide.js
function divide(a, b) {
return a / b;
}
module.exports = divide;
// divide.test.js
const divide = require('./divide');
test('divides 10 by 2 equal to 5', () => {
expect(divide(10, 2)).toBe(5);
});
And it works fine. I run test in the CLI and everything is nice.
I realize that Jest is written with React in mind (hence every guide on Jest uses React) but it seems to make a lot of sense for testing with (vanilla) JavaScript.
I realize that module.exports and require are Node.js specific. But I can't figure how to handle them in a way so that I can use the functions in my browserrendered code.3
Until now I've been solving this problem by commenting out module.exports - and that for sure ain't a viable way.
So my question is: How do I get to use my divide.js both in the test and in the browser?
I can think of to ways to go here:
- Switch the testsuite to something else
- Figure out what tooling or setup I need to create something like a main.js from the files containing module.exports in a way so that it can be used in the browser

Why is Jest still requiring a mocked module?

I am mocking a module using Jest because it contains code that shouldn't run in the test. However I can see from the output that code in the module is being run.
// foo.js
console.log('Hello')
// test.js
jest.mock('./foo')
const foo = require('./foo')
test.todo('write some tests')
Console output
PASS test.js
✎ todo 1 test
console.log foo.js:1
Hello
What's up with that?
This has tripped me up a couple of times.
If you don't provide a mock implementation to jest.mock it will return an object which mirrors the exports of the mocked module but with every function replaced with a mock jest.fn(). This is pretty neat as it is often what you want. But in order to determine the exports of the module, it must first require it. This is what is causing the console.log to be run.
Two possible solutions:
Don't run code in the top level of the module: instead export a function which runs the code.
Provide your own mock implementation so it doesn't need to introspect the module jest.mock('./foo', () => {})

How to import `isOneline` function?

I need to create a custom matcher for Jest test framework, specifically same as .toEqual() but with optional message parameter.
I started with copying everything from actual .toEqual() matcher from here.
I managed to bring all of the the used in this matcher functions except isOneline. It is defined here.
But I do not see how can I import/require it to my code. Is it possible?
Have you tried?
const { isOneline} = require('<path to util.js file>');
Or
const isOneline= require('<path to util.js file>').isOneline;
EDIT:
This works (see comment):
const isOneline = require('expect/build/utils').isOneline;

Unable to unit test an Angular directive that uses $window

I've got a bunch of working unit tests for various Angular (1.4.7) directives, and I'm using Karma, Jasmine and Sinon for testing.
I'm trying to add a unit test for a new directive, which is the only directive I currently have that uses $window but I'm seeing a cryptic error in the console output:
TypeError: 'undefined' is not an object (evaluating 'this.proxy.toString')
This error is coming from sinon.js at line 2372.
I'm doing all the 'normal' things in a directive unit test such as creating a fake element that has the directive as an attribute:
testElement = document.createElement('div');
testElement.setAttribute('data-my-directive');
document.body.appendChild(testElement);
And compiling the directive:
$compile(testElement)($scope);
I'm using $provide to try mock the $window object:
module('app', function ($provide) {
$provide.value('$window', { id: 'test' });
});
But as soon as I try to use $window in the file being tested, the error shown above is thrown.
As I say, I have a bunch of other unit tests for other directives, services and controllers working as expected, so everything appears to be setup correctly. It's just this particular test.
Any ideas?
I am not sure if this is the same bug, but just a couple of days ago a fix to similar issue was got solved on sinon github:
https://github.com/sinonjs/sinon/pull/833
Fix contains lines:
var callStr = this.proxy ? this.proxy.toString() + "(" : "";
where the null check is one thing and several other lines.
This fix is at file lib/sinon/call.js in commit 7a18eb5.
I am not sure if this is same, because file is different and so is line, too. Still, this was so interesting that I would try latest sinon version and see if this gets fixed. It may be though, that similar error is in several parts of sinon, if the coder is for example same in both files.

Sinon and eslint

I am writing unit tests for my angular app with Karma, Jasmine, and Sinon and I run eslint over my code base.
I define global variables that will be used in the beforeEach inject to create a sinon.stub. ESLint keeps complaining that my global variables are defined but never used. For example:
'getListStub' is defined but never used no-unused-vars
but in my code it looks like this
var listService, getListStub;
beforeEach(inject(function(_listService_) {
listService = _listService_;
getListStub = sinon.stub(listService, 'getList').returns(q.when(listResponse));
}
What is the best way to stop ESLint from producing errors?
Is setting /*eslint no-unused-vars: 0*/ at the top of those testing files best?
If you aren't using getListStub anywhere, why are you assigning it to a variable?
The properties of JS closure and memory management (specifically, holding referenced objects) will allow you to use _listService_ directly and you shouldn't need to cache getListStub.
If that does work correctly with sinon, you should be able to rewrite your function as:
beforeEach(inject(function(_listService_) {
sinon.stub(_listService_, 'getList').returns(q.when(listResponse));
}

Categories