how to mock node-redis using jest - javascript

i am using jest and trying to mock node-redis using redis-mock.
// redis.js
const redis = require("redis");
const client = redis.createClient({ host: '127.0.0.1', port: 6379 });
// redis.test.js
const redisMock = require("redis-mock");
describe("redis", () => {
jest.doMock("redis", () => jest.fn(() => redisMock));
const redis = require("./redis");
});
when i run the tests, i get an error
TypeError: redis.createClient is not a function
feels to me that i am doing something wrong when using jest.doMock().
would appreciate your assistance.

The following works for me:
import redis from 'redis-mock'
jest.mock('redis', () => redis)
I do not include the redis library in the test at all, but I include it only in the file which contains the tested class. (The file with tested class is, of course, included in the test file.)

If you are using jest, the switching of the mock and the actual implementation is possible automatically. Works great for CI.
jest.config.js
module.exports = {
// other properties...
setupFilesAfterEnv: ['./jest.setup.redis-mock.js'],
};
jest.setup.redis-mock.js
jest.mock('redis', () => jest.requireActual('redis-mock'));

Related

How to import pg-promise using ES6 syntax?

I am trying to set up a Postgres database in a nodejs server using ES6 syntax, but I don't think I'm importing and initializing pg-promise properly. If I were using common js sytax I would do the below:
// Create Database Connection
const pgp = require('pg-promise')({});
const db = pgp(config.db);
// Test connection
db.connect()
.then((obj) => {
console.log('Connected to database');
obj.done(); // success, release connection;
})
.catch((error) => {
console.error('ERROR:', error.message);
});
Using ES6 I am trying to do the below but the connection just hangs and doesn't complete or error out.
import pgPromise from 'pg-promise';
// Create Database Connection
const pgp = pgPromise({});
const db = pgp(config.db);
// Test connection
db.connect()
.then((obj) => {
console.log('Connected to database');
obj.done(); // success, release connection;
})
.catch((error) => {
console.error('ERROR:', error.message);
});
I've searched through the pg-promise docs and can't find anything about using it with ES6 syntax. Any ideas on what I should change?
The correct as I can see in the documentation.
Loading and initializing the library with Initialization Options:
const initOptions = {/* initialization options */};
const pgp = require('pg-promise')(initOptions);
or without Initialization Options:
const pgp = require('pg-promise')();
Create your Database object from the connection as pgp(connection, [dc]):
const db = pgp(connection);
For ES6 or TypeScript syntax
import pgPromise from 'pg-promise';
const pgp = pgPromise({/* Initialization Options */});
const db = pgp('postgres://username:password#host:port/database');
Is there any error message? Nodejs needs specific conditions to support es module, first make sure you have introduced the module correctly.
// index.mjs
import pgPromise from 'pg-promise';
const pgp = pgPromise({});
console.log(pgp);
Then execute with a --experimental-modules
node --experimental-modules index.mjs
More details https://blog.logrocket.com/es-modules-in-node-js-12-from-experimental-to-release/
Alright this is pretty stupid, but I found out my problem was just that I needed to update the pg-promise dependency. I was using version 8.5.1 and upgrading to 10.5.7 fixed this issue. For anyone else running into this issue you can use the code for ES6 as written in the question just make sure your pg-promise dependency is at the latest version.

Autotests with webpack-dev-server

I'm quite confused with topic.
I develop a some kind of lazy module assembler using webpack-dev-server. It finally works but sometimes we need more assurance. That's why I need some tests. The task is to make them a kind of autotests.
For now the code of server start looks like this (I omit excessive params).
import webpack from "webpack";
import webpackConfig from "../webpack.config.js";
import webpackCompileConfig from "../webpack-compiler.config.mjs";
import WebpackDevServer from "webpack-dev-server";
webpack(webpackConfig(mode, dirname, masterPath)).run(function(err) {
if (err) throw err;
const compileOpt = {
// pack of compiler options
};
const compiler = webpack(webpackCompileConfig(compileOpt));
const server = new WebpackDevServer(compiler, {
// pack of server options
});
server.listen(port, "0.0.0.0", err => {
if (err) throw err;
console.log(`Starting root server on 0.0.0.0:${port}`);
});
});
It starts and works properly: gets some file requests, bundles necessary modules with webpack and sends them to requester.Simple test I want to start with are to check are there files after assembling or not.
Supposed logic is:
Run some command inside this project, e.g. npm run test
It starts server and sends a pack of requests with different logic I want to test (parallel, simultaneous requests etc.)
It tests file existence and send me results in console or smth. of that sort
The problem is my very little expirience in any kind of testing so I'll appreciate your help.
===The way I use it now (spoiler: manually)
The only thing the Internet helps me about.
Server starts as usual
There is another fully off-site test module (code below)
Run mocha
See listed test results
test-server.js
var chai = require("chai");
var chaiHttp = require("chai-http");
const should = chai.should();
chai.use(chaiHttp);
describe("Test file existence", function() {
it("units", done => {
chai
.request("http://localhost:9000")
.get("/units/awesome-project/index.js")
.end((err, res) => {
res.should.have.status(200);
done();
});
});
// another 'it()'s to test other files
});
Yes, it works. But I want more automatisation. Just
Run server
Send requests
Get test results
I'm ready for dialog.
Well.. just sad that nobody ask.
Anyway I've found the answer by myself. And I even wonder how it was freaking easy. It seems that all I need is written here: https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically
So the final result is similar to this:
import fs from "fs";
import path from "path";
import Mocha from "mocha";
const mocha = new Mocha();
const testDir = `${config.dirname}/test/tests`;
fs.readdirSync(testDir)
.filter(file => file.match(/\.js$/))
.forEach(file => {
mocha.addFile(path.join(testDir, file));
});
// somewhere before the devserver start
const runner = mocha.timeout(30000).run();
runner.on("end", () => {
process.exit();
});
I found it at the day I posted this question but there was a hope for someone else to answer (to compare solutions).
Best regards,
Nick Rimer

Running javascript e2e tests on a local appium server

I'm wanting to run e2e tests written in javascript with mocha on an Appium server instance running a local android emulator. The app on test is an apk originally written in react-native.
On Windows I have the server up and running with an Android Studio emulator through using the Appium desktop app. The server all looks good and has the apk of the native app I want to test working fine. I also have a basic describe/assert test written in mocha that I want to apply to the app.
My question is what do I need to include (presumably in the test file) to make the tests actually test the emulator application? I'm finding the documentation pretty confusing and the sample code seems pretty specific to a different use case.
Many thanks for your help!
There are at least 2 good js client libraries to use for Appium based project: webdriverio and wd. Personally, I'm using the second one so I can advice you how write tests with it and mocha:
my test file looks like this:
'use strict'
require(path.resolve('hooks', 'hooks'))
describe('Suite name', function () {
before('Start new auction', async function () {
//do before all the tests in this file, e.g. generate test data
})
after('Cancel auction', async function () {
//do after all the tests in this file, e.g. remove test data
})
it('test1', async () => {
// test steps and checks are here
})
it('test2', async () => {
// test steps and checks are here
})
it('test3', async () => {
// test steps and checks are here
})
})
where hooks.js contains global before/after for all the tests:
const hooks = {}
before(async () => {
// before all the tests, e.g. start Appium session
})
after(async () => {
// after all the tests, e.g. close session
})
beforeEach(async () => {
// before each test, e.g. restart app
})
afterEach(async function () {
// e.g. take screenshot if test failed
})
module.exports = hooks
I'm not saying its the best practice of designing tests, but its one of multiple ways.
Cool so I managed to get it working to a degree. I was checking through the Appium console logs as I was trying to run stuff and noticed that the session id was missing from my requests. All that was needed was to attach the driver using the session id. My code looks a bit like this:
"use strict";
var wd = require("wd")
var assert = require("assert")
var serverConfig = {
host: "localhost",
port: 4723,
}
var driver = wd.remote(serverConfig)
driver.attach("0864a299-dd7a-4b2d-b3a0-e66226817761", function() {
it("should be true", function() {
const action = new wd.TouchAction()
action
.press({x: 210, y: 130})
.wait(3000)
.release()
driver.performTouchAction(action)
assert.equal(true, true)
})
})
The equals true assert is just there as a placeholder sanity check. The only problem with this currently is that I'm copy-pasting the alpha-numeric session id inside the attach method each time I restart the Appium server so I need to find a way to automate that.

how to mock a module in supertest by using jest??

guys!
I am using Jest and Supertest to test my node server code.
Here is my server.js
// server.js
const config = require('./lib/config')
...
const app = new koa()
...
module.exports = app
I want to mock config.js while I used Supertest, here is my server.test.js
// server.test.js
const supertest = require('supertest-as-promised')
describe('xxxxxx', ()=>{
let app,server
beforeEach(()=>{
jest.mock('lib/config',()=>({
uri: '/path',
apiPrefix: '/prefix'
}))
app = require('server')
})
afterEach(()=>{
server && server.close()
app=null
server=null
})
it('should success', async ()=>{
server || (server = app.listen(0))
const request = supertest(server)
request().get('path/prefix_home').expect(200)
})
})
I have printed config in server.js while running test,but the print information showed that jest.mock did not work(path of lib/config is correct).
Anyone has any idea of mocking config.js in such situation by using Supertest??
Jest appear to resolve paths, so the path you provide while mocking has to be consistent: it should be ./lib/config if server.test.js is located next to server.js. If the files are in different places, you'll need to construct the path accordingly, e.g.
../src/lib/config
if your server.js is in src folder and server.test.js is located in test folder next to src

'window is not defined' when testing Paho MQTT Client with mocha and typescript

I googled for days but can't find anything about how to test the Paho MQTT Client. I tried it in a sort of naive way, like that:
import { suite, test, slow, timeout, skip, only } from 'mocha-typescript';
import chai = require('chai');
var jsdom = require('jsdom');
var Paho: any;
const expect: any = chai.expect;
const host: string = '127.0.0.1';
const port: number = 1384;
const clientId1: string = 'testid1';
const clientId2: string = 'testid2';
let client1;
let client2;
describe('test', function () {
it('should', function (done) {
// emulate browser window, which is required by Paho
jsdom.env("<html><body></body></html>", [],
function (err: any, window: any) {
// when window is ready, require Paho and
// initialize with built window
Paho = require('ng2-mqtt/mqttws31').jsdom(window);
// This does not work -> exception in mqttws31.js: window is not defined
client1 = new Paho.MQTT.Client(host, port, clientId1);
client1.connect({ onSuccess: () => { expect(true).to.be.true; done(); }, onFailure: () => { expect(false).to.be.true; } })
done();
});
});
});
However the Paho = require(...)-Part inside the callback function of jsdom.env(...) throws the exception in mqttws31.js: "window is not defined". Has anyone an idea how to solve that, in order to get the Paho Client running in a non-browser environment?
Thanks in advance!
https://www.npmjs.com/package/mochify You could be using similiar NPM module like this. Like you might expect Node.js environment dosen't have browser globals itself so use some library which can integrate these globals to your testing environment.
I am not very familiar with mocha but here's one more library I have played around in Karma as reference https://www.npmjs.com/package/karma-browserify
Or simply using some external service like BrowserStack https://www.npmjs.com/package/browserstack

Categories