Could not resolve module 'fs' webpack - unit-testing

I am trying to unit test my code. I need to test an api call that has a relative url. Am trying to use supertest for api mocks.
Here's a snippet of my test code:
const express = require('express');
const app = express();
const supertest = require('supertest');
app.use(express.bodyParser());
it('should get required details', (done) => {
supertest(app)
.get('/home/api/getdetails')
.expect(200, { response: { foo: 'bar', done);
const expectedActions = [{ type: 'DETAILS',
payload: { foo: 'bar' } }];
const store = mockStore({}, expectedActions);
const func = getDetails();
// eslint-disable-next-line
console.log("func"+func);
const dispatch = sinon.spy();
func(dispatch);
expect(store.getActions()).
to.deep.equal(expectedActions);
});
Here's my webpack.config.js
var path = require('path');
var env = require('./env');
// List of allowed environments
var allowedEnvs = ['env1', 'env2', 'env3', 'env4', 'env5', 'env6', 'env7', 'env7'];
// Get available configurations
var configs = {
env0: require(path.join(__dirname, 'cfg/env0')),
env1: require(path.join(__dirname, 'cfg/env1')),
env2: require(path.join(__dirname, 'cfg/env2')),
env3: require(path.join(__dirname, 'cfg/env3')),
env4: require(path.join(__dirname, 'cfg/env4')),
env5: require(path.join(__dirname, 'cfg/env5')),
env6: require(path.join(__dirname, 'cfg/env6')),
env7: require(path.join(__dirname, 'cfg/env7')),
env8: require(path.join(__dirname, 'cfg/env8')),
};
/**
* Get an allowed environment
* #param {String} env
* #return {String}
*/
function getValidEnv(env) {
var isValid = env && env.length > 0 && allowedEnvs.indexOf(env) !== -1;
return isValid ? env : 'dev';
}
/**
* Build the webpack configuration
* #param {String} env Environment to use
* #return {Object} Webpack config
*/
function buildConfig(env) {
var usedEnv = getValidEnv(env);
return configs[usedEnv];
}
module.exports = buildConfig(env);
Everywhere, it is said that just by adding,
node:{
fs: 'empty',
}
would solve the issue. But, the issue is not resolved for me.
Could anyone please help me with this?
Thank you,
Aswini J

Related

Cannot POST when sending request in Postman

I am having a small issue. I am trying to send a request in Postman, but I receive "
Cannot POST /api/logTemp/1/25
"
Here is my app.js:
const express = require('express')
const bodyParser = require('body-parser')
const cors= require('cors')
const fs= require('fs')
const path= require('path')
const morgan = require('morgan')
const router = require('./routes/route')
const app = express()
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false}))
// parse application/json
app.use(bodyParser.json())
app.use(morgan('dev'))
//create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, '/logs/access.log'), {flags: 'a'})
//setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
app.use(router)
app.get('/', (req, res) => {
res.send('Hello World!')
})
const port = 3000
//app.listen(process.env.PORT || port, (err) => {
app.listen(port, () => {
console.log('Server started running on :' + port)
})
and here is my controller file:
const { getEnabledCategories } = require('trace_events');
const mysql = require('../database/db')
class MainController {
async logTemp(req, res){
console.log(req.params.temperature)
console.log(req.params.deviceID)
if(req.params.deviceID != null && req.params.temperature != null){
let deviceID = req.params.deviceID
let temperature = req.params.temperature;
var sql = `insert into log_temp (log_date, device_id, temp) values (now(),${deviceID}, ${temperature});`
mysql.query(sql, (error,data,fields) => {
if(error){
res.status(500)
res.send(error.message)
} else{
console.log(data)
res.json({
status: 200,
message: "Log uploaded successfully",
affectedRows: data.affectedRows
})
}
})
} else {
res.send('Por favor llena todos los datos!')
}
}
async getLogs(req, res){
console.log("Get Logs")
console.log(req.params.deviceID)
if(req.params.deviceID!=null){
let deviceID = req.params.deviceID;
var sql = `SELECT * FROM log_temp where device_id=${deviceID}`
mysql.query(sql, (error, data, fields) => {
if(error) {
res.status(500)
res.send(error.message)
} else {
console.log(data)
res.json({
data
})
}
})
}
}
}
const tempController = new MainController()
module.exports = tempController;
The code above was made in Visual Studio. It is odd because getLogs does work but logTemp does not. What I intend to do with logTemp is add a new value (which is the value temperature) to MySQL database. The connection to the database worked just fine, as well as localhost. If you need any more info in order to help me find a solution, please let me know and I will be more than happy to provide it. Also, i'm sorry for any grammar errors, english is not my first language :)

export 'encrypt' (imported as 'encrypt') was not found in '#aws-crypto/client-browser'

I am trying to encrypt data using AWS Encryption SDK for javascript(react) in browser but getting this error : export 'encrypt' (imported as 'encrypt') was not found in '#aws-crypto/client-browser'
import { KmsKeyringBrowser, encrypt } from "#aws-crypto/client-browser";
const generatorKeyId = '*********************'
const keyIds = ['**************************']
const keyring = new KmsKeyringBrowser({generatorKeyId,keyIds})
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
origin: 'us-west-2'
}
const encryptData = async (data) => {
const result = await encrypt(keyring,data, { encryptionContext: context })
console.log(result);
}
I have alos tried using buildEncrypt but it is not working. Below is the code :
import { KmsKeyringBrowser, encrypt } from "#aws-crypto/client-browser";
const generatorKeyId = '*********************'
const keyIds = ['**************************']
const keyring = new KmsKeyringBrowser({generatorKeyId,keyIds})
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
origin: 'us-west-2'
}
const encryptData = async (data) => {
const result = await buildEncrypt({encrypt: (keyring,data, { encryptionContext: context })} )
console.log(result);
}
I am unable to find out what I was doing wrong. Any help would be apprecieated. Thankyou

Swagger codegen - swift 3 ignore params

There is a problem with header params in Swagger Codegen. my RAML file looks like that :
---...---
parameters:
timeParam_begin:
in: header
name: timeframe_begin
type: string
timeParam_end:
name: timeframe_end
in: header
type: string
recommendationsParam:
name: recommendations
in: header
default: 3
type: number
--- ....----
and later
---...----
post:
summary: Search for possible coordinates given an address
parameters:
- $ref: '#/parameters/timeParam_begin'
- $ref: '#/parameters/timeParam_end'
- $ref: '#/parameters/recommendationsParam'
---...----
Until here EVERYTHING IS GOOD, the validation is ok and the parameters works well.
But...
when I export it in swift (1,2 or3) there is a problem :
/**
- POST /tasks
- Add 'Task' object.
- examples: [{contentType=application/json, example="Task added succesfully"}]
- parameter task: (body) task object
- returns: RequestBuilder<String>
*/
open class func tasksPostWithRequestBuilder(task: Task) -> RequestBuilder<String> {
let path = "/tasks"
let URLString = SwaggerClientAPI.basePath + path
let parameters = task.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<String>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
No more headers parameters !
I try to export it in PHP and typescript, the parameters are here !!!!! :
Typescript Angular2 :
/**
*
* Add 'Task' object.
* #param task task object
* #param timeframeBegin
* #param timeframeEnd
* #param recommendations
*/
public tasksPostWithHttpInfo(task: models.Task, timeframeBegin?: string, timeframeEnd?: string, recommendations?: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/tasks`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'task' is not null or undefined
if (task === null || task === undefined) {
throw new Error('Required parameter task was null or undefined when calling tasksPost.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/x-www-form-urlencoded'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: task == null ? '' : JSON.stringify(task), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = this.extendObj(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
PHP :
/**
* Operation tasksPostWithHttpInfo
*
*
*
* #param \Swagger\Client\Model\Task $task task object (required)
* #param string $timeframe_begin (optional)
* #param string $timeframe_end (optional)
* #param float $recommendations (optional, default to 3.0)
* #throws \Swagger\Client\ApiException on non-2xx response
* #return array of string, HTTP status code, HTTP response headers (array of strings)
*/
public function tasksPostWithHttpInfo($task, $timeframe_begin = null, $timeframe_end = null, $recommendations = null)
{
// verify the required parameter 'task' is set
if ($task === null) {
throw new \InvalidArgumentException('Missing the required parameter $task when calling tasksPost');
}
// parse inputs
$resourcePath = "/tasks";
$httpBody = '';
$queryParams = [];
$headerParams = [];
$formParams = [];
$_header_accept = $this->apiClient->selectHeaderAccept(['application/x-www-form-urlencoded']);
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);
// header params
if ($timeframe_begin !== null) {
$headerParams['timeframe_begin'] = $this->apiClient->getSerializer()->toHeaderValue($timeframe_begin);
}
// header params
if ($timeframe_end !== null) {
$headerParams['timeframe_end'] = $this->apiClient->getSerializer()->toHeaderValue($timeframe_end);
}
// header params
if ($recommendations !== null) {
$headerParams['recommendations'] = $this->apiClient->getSerializer()->toHeaderValue($recommendations);
}
// default format to json
$resourcePath = str_replace("{format}", "json", $resourcePath);
// body params
$_tempBody = null;
if (isset($task)) {
$_tempBody = $task;
}
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} elseif (count($formParams) > 0) {
$httpBody = $formParams; // for HTTP post (form)
}
// make the API Call
try {
list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
$resourcePath,
'POST',
$queryParams,
$httpBody,
$headerParams,
'string',
'/tasks'
);
return [$this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders());
$e->setResponseObject($data);
break;
case 500:
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders());
$e->setResponseObject($data);
break;
}
throw $e;
}
}
WHY CODEGEN FAILS ????? please help. is there a way to force the generation of code ?

Angular 2.0.0 Use of reserved word 'import' at karma-test-shim.js - including Angular TypeScript file in JS output?

After upgrade to Angular 2.0.0 I'm getting this error from PhantomJS:
START:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
SyntaxError: Use of reserved word 'import'
at karma-test-shim.js:4115
Chrome 53.0.2785 (Mac OS X 10.11.6) ERROR
Uncaught SyntaxError: Unexpected token import
at http://localhost:9876/context.html:8
When I look at karma-test-shim.js at line 4115 in Chrome DevTools I find that it's trying to include the ts for #angular/core/testing:
eval("/**
* #license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector, NgModule, NgZone, OpaqueToken } from '#angular/core';
import { AsyncTestCompleter } from './async_test_completer';
import { ComponentFixture } from './component_fixture';
import { ListWrapper } from './facade/collection';
import { FunctionWrapper, stringify } from './facade/lang';
import { TestingCompilerFactory } from './test_compiler';
var UNDEFINED = new Object();
/**
* An abstract class for inserting the root test component element in a platform independent way.
*
* #experimental
*/
export var TestComponentRenderer = (function () {
function TestComponentRenderer() {
}
TestComponentRenderer.prototype.insertRootElement = function (rootElementId) { };
return TestComponentRenderer;
}());
var _nextRootElementId = 0;
/**
* #experimental
*/
export var ComponentFixtureAutoDetect = new OpaqueToken('ComponentFixtureAutoDetect');
/**
* #experimental
*/
export var ComponentFixtureNoNgZone = new OpaqueToken('ComponentFixtureNoNgZone');
/**
* #experimental
*/
export var TestBed = (function () {
...
My webpack.test.config (this package only has test)
process.env.npm_lifecycle_event = 'test';
var webpack = require('webpack'),
basicConf = {},
path = require('path');
var NODE_MODULES = root("node_modules");
// Helper functions
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
basicConf.entry = {};
basicConf.devtool = "eval";
basicConf.debug = true;
basicConf.resolve = {
cache: true,
fallback: [ NODE_MODULES ],
modulesDirectories: [ NODE_MODULES ],
root: [ root("") ],
extensions: ["", ".ts", ".js", ".json", ".css", ".scss", ".html"]
};
basicConf.module = {
loaders: [
{
test: /\.ts$/,
loader: "ts",
query: {
"ignoreDiagnostics": [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 -> Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375, // 2375 -> Duplicate string index signature
2502 // 2502 -> Referenced directly or indirectly
]
}
},
{test: /\.scss$/, loader: "null"},
{test: /\.css$/, loader: "null"},
{test: /\.html$/, loader: "raw"},
{test: /\.json$/, loader: "json"}
],
postLoaders: [
{
test: /\.(js|ts)$/,
include: path.resolve("."),
loader: "istanbul-instrumenter-loader",
exclude: [/.+-spec\.ts$/, /\.e2e\.ts$/, NODE_MODULES]
}
]
};
module.exports = basicConf;
What would be causing webpack/karma to include a ts file in the karma-test-shim.js output? This code can be leveraged by another project and executes correctly. I just can't seem to run the tests.
My actual karam.test.shim.js:
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
require('ts-helpers');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('rxjs/Rx');
require("material-design-lite/dist/material.min.js");
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(
browser.BrowserDynamicTestingModule,
browser.platformBrowserDynamicTesting()
);
var testContext = require.context('.', true, /.+-spec\.ts/);
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
var modules = requireAll(testContext);
Simply put, must migrate to webpack 2.0.0-beta.25

Why does `binary operation argument type newval is not compatible with type string` appear

I have the following code and inside of it the WebStorm inspection Binary operation argument type newVal is not compatible with type string appears:
I'm wondering why
Full module code:
define(function (require) {
"use strict";
var ng = require('angular');
require('../ngModule').directive('downloadFile', ['$parse', 'auth.authService', function ($parse, authService) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var getter = $parse(attrs.downloadFile);
scope.$watch(getter, function (path) {
if (path !== "") {
var form = document.createElement("form");
var element1 = document.createElement("input");
var element2 = document.createElement("input");
form.method = "POST";
form.action = path;
element1.value = authService.getToken();
element1.name = "Authorization";
form.appendChild(element1);
element.append(form);
form.submit();
element.empty();
}
});
}
};
}]);
});
AngularJS's JSDoc definition makes WebStorm think the path argument is a boolean.
You can make WebStorm stop complaining by adding your own JSDoc:
if (path !== /** #type {boolean} */"") {