JestJS testing synchronous code shows asynchronous behavior - jestjs

I am new to JestJS and trying to test synchronous code. The following test passes alright:
bin = new Compiler().compile('{int a = 42;}');
test('Integer constant declaration', function() {
expect(bin.dumpVariables()).toBe("[int const a = 42]\n");
});
However when I append this code:
bin = new Compiler().compile('{bool b;}');
test('Another test', function() { ... }
... the first test fails because bin already has the new value from the assignment that comes after it. Why is that? My code is fully synchronous so I would have expected the first test to pass and THEN the effects of the code that follows it.

Cause bin lives in the scope of both test. But the main problem is that all code that is written outside of one of the test, describe, it blocks and so on is called immediately. Lets have a look how a test call looks like:
test('testname', testFunction)
this means the test is added to test suite with a name and a function, but this doesn't mean that the testFunction is called immediately. If it would work like this a beforeEach block wouldn't work. So first the test suite collects all the different test, describe, it calls and then it runs them. If you now create a variable in the upper scope outside of the tests it will have the value that was assigned to last. In your case {bool b;}

Related

Is there a way to test functions with Jasmine without exposing them?

I have a utils.js file with some generic utility functions. I use module.exports to expose some of the functions while keep the rest hidden.
module.exports = {
utils_1: function_1,
utils_2: function_2
};
Suppose there are other functions, namely function_3 and function_4 that I would like not to expose, yet I want to test with Jasmine. The only way I can currently do it is by exposing them with the rest of the functions and writing my test suites as usual.
Is there a way to test some functions via Jasmine while not exposing them?
The only thing I can think of is creating a different javascript file containing (and exposing) function_3 and function_4, require that file in my utils.js and at the same time test the new file with Jasmine, but this would split my original file in two (and the same would apply for all other similar files).
function_3 and function_4 are used inside function_1 and function_2, right? So, do you really need to unit test it? I would not. But other people might think the contrary.
Here is my example
// utils.js
function function_3(obj) {
obj.a = 3;
return obj;
}
function function_4(obj) {
obj = function_3(obj); // invoke function_3
obj.b = 4;
return obj;
}
module.exports = { utils_4: function_4 };
The test:
const { utils_4 } = require('utils');
describe('test 1', () => {
it('should pass', () => {
const obj = utils_4 ({});
expect(obj.a).toBeDefined();
expect(obj.a).toEqual(3);
expect(obj.b).toBeDefined();
expect(obj.b).toEqual(4);
});
});
It should pass, right? See that I only test function_4, but, if I change the implementation of function_3 in a way that brakes my test, the test will detect it.
If we change function_3 to
function function_3(obj) {
obj.c = 3;
return obj;
}
The test will fail.
This is an awful example but it is just illustrative. Take the good part of it. But again, other people might think the contrary and will go with an approach to test function_3 directly. Use a coverage lib to see what is covered by your tests.
Hope it helps
Your private / unexposed functions are used within your exported functions, are they not? Thereby, they are tested implicitly as soon as you write all the test cases for your public / exposed functions.
Exposing functions or writing tests on private functions is missing the goal of unit tests: Testing the public interface.
Think of private / unexposed methods as implementation details. You should not write tests for those, as the private methods are abstracting the implementation detail. It becomes tedious and over-complicated to have tests break because some internal behavior changed slightly.
You should be able to refactor or rewrite private functions at a whim, yet as long as they public interface is fulfilled, your tests shall remain green.
It may make sense to create a new module for your function_3 and function_4, depending on what they are doing for you. If I discover, that I want to test something internally, that's a sign to make it into its own module, with its own public interface.
So I'd say that your intention of moving the functions into a different JavaScript file is actually the right idea. (Yet you may realize that here only function_3 needs to be exposed, whereas function_4 can still be hidden).

synchronous require so entire Node.js script isn't in callback

When using WebAssembly, there is a callback for onRuntimeInitialized(). You basically can't do anything until it happens.
So if you have a library that is implemented in it, you have to say:
var mylib = require('mylib')
mylib.onRuntimeInitialized = function() {
...
// Anything that wants to use *anything* from mylib
// (doesn't matter if it's synchronous or asynchronous)
...
}
On the plus side, you're not making Node wait to do any initialization that might not rely on mylib...so other modules can be doing fetches or whatever they need. On the negative side, it's pretty bad ergonomics--especially if everything you're doing depends on this library.
One possibility might seem to be to fold the initialization waiting into a promise, and then wait on it:
var mylib = require('mylib')
await mylib.Startup()
But people apparently write about how much they don't like the idea of top-level AWAIT. And my opinion on it is fairly irrelevant either way, as it's not allowed. :-/
So is there really no way to hold up code at the top level besides wrapping the whole app in a callback?
One thing to note with Node is that requires will return the same object, no matter what file that require is called in. Order does matter, but it will be the same object in all files.
So in your main index.js you could do something like
var myLib = require('mylib')
myLib.libby = myLib.initialize()
and then in another file, doesStuff.js, you can do:
const libby = require('mlib').libby
module.exports = function doStuff() {
/* do stuff with initialized libby object */
}
Typically the way this works is that call in doStuff.js is not called until everything is initialized and say the web route is handled. So your server is running already and so libby will be initialized and ready to use once it's called.
If you have something that absolutely cannot fail, like the server will not run if DB connection is not successful or something, then waiting is appropriate, so yes, you'd need to wrap everything (at least the core of your actions) in a callback so your server knows when it's safe to start.

Proper use of artifacts.require?

I am trying to understand how artifacts.require should be used. I've seen the standard paragraph describing it as being for migrations and testing. From this I infer that the globally scoped artifacts with its method require are automatically defined by the truffle executable tool when doing migrations or running tests. However, I am working with some code that uses artifacts.require outside the context of any migrations or tests, rather, this code just needs to do the usual at and new. However, in this context, the object artifacts is not defined.
Do I have the right picture here? Is this an appropriate use of artifacts.require? If so, what must be done to make it be defined outside of migrations and testing?
Thanks for any suggestions!
artifacts.require really isn't meant to be used outside of a test. this is where it is defined: https://github.com/trufflesuite/truffle-core/blob/3e96337c32aaae6885105661fd1a6792ab4494bf/lib/test.js#L240
when in production code you should load the compiled contract into your application using truffle-contract https://github.com/trufflesuite/truffle-contract
here is a short example (from http://truffleframework.com/docs/getting_started/packages-npm#within-javascript-code and see
http://truffleframework.com/docs/getting_started/contracts#making-a-transaction )
var contract = require("truffle-contract");
var contractJson = require("example-truffle-library/build/contracts/SimpleNameRegistry.json");
var SimpleNameRegistry = contract(contractJson);
SimpleNameRegistry
.deployed()
.then(function(instance) {
return instance.setRegistry(address);
})
.then(function(result) {
// If this callback is called, the transaction was successfully processed.
alert("Transaction successful!")
})
.catch(function(e) {
// There was an error! Handle it.
});

Immediately invoked function expression isn't executed on second require

Here is a sample code to make it more clear.
This is my module:
module.exports = ((parameter) => {
console.log(parameter);
})('some value');
mymodule is actually the main server file and thus has to be executed immediately.
My unit tests in test suite require my module but the immediately invoked function expression is executed only first time.
require('./mymodule');
require('./mymodule');
How can I make this run every time ?
You can invalidate the cache that Node maintains:
require('./mymodule');
delete require.cache[require.resolve('./mymodule')]
require('./mymodule');
You are probably better off though with exporting the function and calling it when needed, instead of only exporting the result.
From nodejs docs:
Multiple calls to require('foo') may not cause the module code to be
executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles.
https://nodejs.org/docs/v0.4.12/api/modules.html#caching
If you want to have a module execute code multiple times, then export a function, and call that function.

Wanted but not invoked: However, there were other interactions with this mock:

Wanted but not invoked: However, there were other interactions with this mock:
This is a mockito error you would catch when trying to verify the invocation on an object on specific method, but what happens is you have interacted with other method of that object but not the one mentioned.
If you have an object named CustomerService and say it has two methods named saveCustomer() and verifyExistingCustomer(),
and your mockito looks something like verify(customerService, atleast(1)).verifyExistingCustomer(customer), but in your actual service you called the saveCustomer() at least one.
Any idea how to resolve this ?
From what you are describing, it looks like you are telling your mocks that you are expecting verifyExistingCustomer() to be called but you are not actually calling it.
You should probably look at your test design, specifically ensuring that you can (via mocking) isolate your tests to test each method individually.
If there is something in your code that decides whether to call saveCustomer() or verifyExistingCustomer() then you should try to mock the data that the code inspects so that you can test each individually.
For example if your code looked like this:
if (customer.getId() == 0) {
saveCustomer(customer);
} else {
verifyExistingCustomer(customer);
}
Then you could have two separate tests that you could isolate by setting a zero value and non-zero value for the id in customer.
If you'd like to share your code I could probably give you a better example.

Resources