I have a test file with a number of tests and a utility function exported
export function createObjects(){
const numObjects = 100;
const objects = [];
for (let i = 1; i < numObjects + 1; i++) {
objects.push(i);
}
return objects
}
describe('Test describe', () => {
it('Test', () => {
})
})
I am trying to import the createObjects function in another test. However when I import the function like below in the second test
import {createObjects} from './TestOne'
It runs the entire test suite. Any idea why this happens?
I'm using jest 24.9.0
Related
Beginner Level - Unit Testing
Here's the function
export function toHex(number) {
const nstr = number.toString(16);
if (nstr.length % 2) {
return `0${nstr}`;
}
return nstr;
Able to figure out if the function is true or not by running the following Unit testing code:
// testing new function
describe('toHex', () => { //mocking the method
test('Testing Function toHex ', () => { // declaring the method
const str = 14 // initial value
const actual = toHex(str) // calculate the value
expect(actual).toMatchSnapshot(); // checking whether is true
})
});
Now how could I add different scenarios and make the following function to pass / Fail
Thanks
I am reviewing some design patterns in JavaScript. My first design pattern is the module pattern. After researching a bit I built the following example:
var CarCostEstimation = (function() {
//Let's imagine script is getting best price from different api's
function getBestMotorCost() {
return 3000;
}
function getBestChasisCost() {
return 1000;
}
function getBestWheelsCost() {
return 400;
}
return {
getEstimatedCost: function() {
var chasisCost = getBestChasisCost();
var motorCost = getBestMotorCost();
var wheelsCost = getBestWheelsCost();
return chasisCost + motorCost + wheelsCost;
}
}
})();
var totalCost = CarCostEstimation.getEstimatedCost();
console.log(totalCost);
I have two doubts:
If the way I am calling the "private" methods, in my public method is the correct one.
If I want to add this CarCostEstimation module to another Estimation module, how would it do it?
For point 2:
var CostEstimation = (function() {
var estimationObject;
function sumDifferentEstimations() {
estimationObject.getEstimatedCost();
}
return {
addEstimationObjetc: function(object) {
estimationObject = object
},
getTotalCost: function() {
return sumDifferentEstimations();
}
}
})();
Another way to define your functions. (I'm also using some ES6 syntax)
const CarCostEstimation = function() {
return {
getBestMotorCost: () => 3000,
getBestChasisCost: () => 1000,
getBestWheelsCost: () => 400,
getEstimatedCost: function() {
const chasisCost = this.getBestChasisCost();
const motorCost = this.getBestMotorCost();
const wheelsCost = this.getBestWheelsCost();
return chasisCost + motorCost + wheelsCost;
}
}
}();
const totalCost = CarCostEstimation.getEstimatedCost();
console.log(totalCost);
To export your function as a module, you could use the export statement from ES6 and import your module using the import statement
https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
I am writing a custom operator to load a csv file and emit each line as data. This operator is supposed to work like the of operator, which is a static function to create observable. I follow the instruction of operator creation and add the operator function directly to Observable prototype.
All following code is written in JavaScript ES6.
My source code is this
import { Observable } from 'rxjs';
import { createInterface } from 'readline';
import { createReadStream } from 'fs';
function fromCSV(path, options) {
return Observable.create((subscriber) => {
let readStream = createReadStream(path);
let reader = createInterface({ input: readStream });
let isHeader = true;
let columns;
reader.on('line', (line) => {
if (isHeader) {
columns = line.split(',');
isHeader = false;
} else {
let values = line.split(',');
let valueObject = {};
for (let i = 0, n = columns.length; i < n; i++) {
valueObject[columns[i]] = values[i] || undefined;
}
subscriber.next(valueObject);
}
});
reader.on('close', () => subscriber.complete());
readStream.on('error', (error) => subscriber.error(error));
});
}
Observable.prototype.fromCSV = fromCSV;
The operator function looks totally correct, but when I try to use this operator like
import { Observable } from 'rxjs';
import './rx-from-csv';
Observable.fromCSV(testCSV)
.subscribe((row) => {
console.log(row);
});
It throws an error TypeError: _rxjs.Observable.fromCSV is not a function. So the function binding fails and I have no idea why it happens :-( Any help is appreciated.
This particularly confuses me because I have successfully done a similar operator binding for another custom csv operator.
The problem is that TypeScript doesn't know about the operator because it couldn't find it in RxJS's *.d.ts.
Have a look at how it's done by the default RxJS operators: https://github.com/ReactiveX/rxjs/blob/master/src/add/operator/bufferCount.ts
In you case you'll need just the declare module ... part with a correct path to the Observable definition. For example:
function fromCSV(path, options) {
...
}
Observable.prototype.fromCSV = fromCSV;
declare module 'rxjs/Observable' {
interface Observable<T> {
fromCSV: typeof fromCSV;
}
}
It turns out that I used a wrong way to add static function. See this post for more information.
To add a static function to the Observable class, the code needs to be
Observable.fromCSV = fromCSV;
Adding the function to the class's prototype will make it only available after newing that class.
I am developing a simple javascript module for learning purposes. It looks like following:
function gen (props) {
var test = [];
for(var i = 0; i < 10; i++) {
test.push(props.start + i);
}
return test;
}
module.exports = function (props) {
return gen(props)
}
I am calling this module as:
<script>
import gen from './gen.js'
...
mounted: function () {
var x = gen({start: 5});
console.log(x);
}
...
</script>
But I am getting Converting circular structure to JSON error. What am I doing wrong?
EDIT: Forgot to mention, this is in VueJS. The whole module is a separate file and I am importing it into one of components.
I want to organize my project imports with browserify so that I have a global utils variable from which I can call and execute functions much like jquery's $.
So in the end I want something like:
window.utils = ...
So I can use utils.aFunction();
I also want to divide my dependencies in several files, as an example, this would be my project:
libs
|_ math.js //Implements randomInt and RandomFloat methods
|_ connection.js //Implements isConnected method
utils.js //Calls all the required dependencies
My idea so far is to have something like this:
In libs/math.js:
module.exports = {
randInt: function() {
return 4;
},
randFloat: function() {
return 4.1;
}
};
And then I would do in utils.js:
var math = require('./libs/math');
var connection = require('./libs/connection');
var libs = [math, connection];
var utils = {};
for (var i = 0; i < libs.length; i++) {
for (var key in libs[i]) {
utils[key] = libs[i][key];
}
}
window.utils = utils;
This actually works just fine, but I don't know if it wasn't already solved by a library.
I have a feeling there are more efficient ways of doing this, what would be the recommended approach with browserify?
The code for throwing things into util object is definitely odd looking, and I wouldn't recommend this looping over all your required util submodules.
var libs = [math, connection];
var utils = {};
for (var i = 0; i < libs.length; i++) {
for (var key in libs[i]) {
utils[key] = libs[i][key];
}
}
If you were using a common js approach with webpack/browserify, you would simply declare your util to be global in the configuration file, and simply add the needed module.exports inside of your util.js
//connect.js
module.exports = {
isConnected: function(){
return true;
}
};
//math.js
module.exports = {
randInt: function() {
return 4;
},
randFloat: function() {
return 4.1;
}
};
//utils.js
exports.math = require('./math');
exports.connect = require('./connect');
//test.js
var utils = require('./utils');
console.log(utils.math.randInt());
console.log(utils.connect.isConnected());