How can I use test database for intern testing - intern

I am using intern for testing in my node project, however I don't know how to set up the intern properly so that it uses 'test' database instead of 'development' database. I was trying to put the code process.env.NODE_ENV = 'test' into my test file, but it doesn't work. My intern.js file is just the default file and my intern running command is /node_modules/.bin/intern-client config=tests/intern. All the test run properly except the data was generated in the development database not the test database. Anyone knows how to fix it? Thank you!
Here is one of my test case in my test suite, which add the data to the database
tdd.test('normal user creation', function(){
var name = chance.name();
return models.User.create({
name: name,
gender: chance.gender(),
email: chance.email(),
balance: 0.0,
phone_number: chance.phone({country: 'ca', mobile: true})
}).then(function (user) {
return assert.strictEqual(name, user.name, 'user name should ' +
'be equal to each other');
}).catch(function (error) {
throw new Error(error.message);
});
});

Finally, I found the solution. In the package.json file, set the scripts option as
"scripts": {
"start": "node src/index.js",
"test": "set NODE_ENV=test&&intern-client config=tests/intern"
},
then run npm test, the intern will run the test base on test database now

Related

How to run the same e2e tests on different enviroments in playwright

I have a set of e2e tests.
We have a test enviroment: test.mypage.com
And we also have a UAT enviroment: uat.mypage.com
I want to be able to run the same e2e tests on either our test or uat enviroment, depending on the command line i use.
my config file:
import { LaunchOptions } from 'playwright';
const browserOptions: LaunchOptions = {
headless: false,
slowMo: 0,
args: []
};
export const config = {
browserOptions,
env: {
server: 'test'
}
};
my step file:
Given(/^i go to login page$/, async function () {
await PW.page.goto(`https://${config.env.server}.mypage.com/`);
});
the command line I use to run my tests:
npx cucumber-js
So I assume the solution would be something like
npx cucumber-js --server "uat"
but either my syntax is wrong or I'm missing something. When I run the script above, I get an error: unknown option: '--server'.
I tried
npx cucumber-js `$env:server="uat"
which didn't throw any errors but the environment remained test.mypage.com.
So how can I change the environment from the command line?
You can use the baseurl test option for this.
In your config file, add the baseurl:
import { PlaywrightTestConfig } from '#playwright/test';
const config: PlaywrightTestConfig = {
use: {
baseURL: `https://${config.env.server}.mypage.com/`,
},
};
export default config;
So now your test should look like this:
Given(/^i go to login page$/, async function () {
await PW.page.goto('/');
});
Now from CLI, you can run with a different baseurl like this:
URL=https://playwright.dev npx playwright test

React-Native Server Error When making a simple API request

I have a frontend in react-native that makes an API call using the axios library; its shown below:
function addItem(item) {
if (!item) {
Alert.alert('Error', 'Please enter a valid item.', [{text: 'Ok'}]);
} else {
axios.get('/additem', {
Id: items[items.length - 1].id + 1,
Text: item
})
.then((res) => {
setItems([...items, {id: res.id, text: res.text}])
})
.catch((err) => {
console.log(err);
})
}
}
As you can see, I am making a GET request to an endpoint, and using the response data.
Here is what my backend endpoint looks like in Node.js (using Express.js):
app.get('/additem', (req, res) => {
const item = new Item({
id: req.body.Id,
text: req.body.Text
});
item.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err)
})
})
The save() function and Item object are just specific to MongoDB, so don't worry too much about that.
I am using a proxy to "connect" the backend and frontend, meaning, I have added this to my package.json file in my frontend:
{
"name": "firstProj",
"version": "0.0.1",
"private": true,
"proxy": "https://localhost:5000",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
localhost:5000 is where my node.js backend is running
Now when I try to access the endpoint via my frontend, react-native yells at me saying this:
LOG [Error: Network Error]
Zero clue why this is happening. Any help is appreciated. :) Let me know if you need more information from my end.
Thanks a ton.
EDIT:
this is the full error when not caught by my code:
Possible Unhandled Promise Rejection (id: 0):
Error: Network Error
createError#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:99656:26
handleError#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:99560:27
dispatchEvent#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:32348:31
setReadyState#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:31432:33
__didCompleteResponse#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:31248:29
emit#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:3537:42
__callFunction#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2765:36
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2497:31
__guard#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2719:15
callFunctionReturnFlushedQueue#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2496:21
callFunctionReturnFlushedQueue#[native code]
just Remember to not put http://localhost:PORT into API Address because it will not work in that way
the way you should do it is first find your internet IP address on your machine like :
108.67.122.124
and then you change setting in your backend Service and replace localhost with this :
108.67.122.124:PORT
and then Address it like that to your AXIOS or whatever library you use
So lets wrap it again :
DONT address your react native like http:localhost:5000 instead do it like 108.67.122.124:5000 In that way it will fully work

How do I dynamically add TypeOrm configurations from a secrets store when generating migrations?

I'm trying to set up a postgres connection with TypeOrm that dynamically pulls configurations from a secrets source (asynchronously) and generates a new migration.
I've attempted to use async await to asynchronously set both environment and local variables that will be used by the postgres.config.ts file when the typeorm-cli runs, but i continually get errors.
// src/config/defaults/postgres.config.ts
const postgresConfig = (async () => {
try {
const db: PostgresConfig = await secretsSource.getSecret();
return {
type: 'postgres',
host: db.host,
port: db.port,
username: db.username,
password: db.password,
database: db.database,
entities: [path.join(__dirname, '../**/*.entity{.ts,.js}')],
migrationsRun: true,
logging: true,
logger: 'file',
migrations: [path.join(__dirname, '../migrations/**/*{.ts,.js}')],
cli: {
migrationsDir: 'src/migrations',
},
} as ConnectionOptions;
} catch (error) {
// ... handle error
}
})();
export default postgresConfig;
// package.json
{
scripts: {
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/defaults/postgres.config.ts",
"typeorm:migrate": "npm run typeorm migration:generate -- -n",
"typeorm:run": "npm run typeorm migration:run"
}
};
I expect that when running "npm run typeorm:migrate initial", the script will point back to the config file run the file asynchronously, wait for the code to provide the necessary DB configurations, and generate migrations, but it seems that the script doesn't run any of the code as expected and I continually get the following error:
Error during migration generation:
{ MissingDriverError: Wrong driver: "undefined" given. Supported drivers are: ..... }
I need dynamically fetch db configurations because I have different environments that require different configurations.

Automated Testing with Databases

I'm fairly new to automated testing and was wondering how I should go about writing tests for the database. The project I'm working on right now is running PostgreSQL with Sequelize as the ORM on a Node.JS environment. If it matters, I'm also using Jest as the testing library right now.
In my app I use a config module to control configuration settings for different environments. When running tests the process.env.APP_ENV is set to test, and it will set the dialect to sqlite. Note that you will not have any data or data persistence, so you will need to populate it with all the data needed for your tests.
Include sqlite3
yarn add -D sqlite3
or
npm i -D sqlite3
Config
module.exports = {
database: {
name: 'dbname',
user: 'user',
password: 'password',
host: 'host',
// Use "sqlite" for "test", the connection settings above are ignored
dialect: process.env.APP_ENV === 'test' ? 'sqlite' : 'mysql',
},
};
Database/Sequelize
// get our config
const config = require('../config');
// ... code
const instance = new Sequelize(
config.database.name,
config.database.user,
config.database.password,
{
host: config.database.host,
// set the dialect, will be "sqlite" for "test"
dialect: config.database.dialect,
}
);
Test Class (Mocha)
const TestUtils = require('./lib/test-utils');
describe('Some Tests', () => {
let app = null;
// run before the tests start
before((done) => {
// Mock up our services
TestUtils.mock();
// these are instantiated after the mocking
app = require('../server');
// Populate redis data
TestUtils.populateRedis(() => {
// Populate db data
TestUtils.syncAndPopulateDatabase('test-data', () => {
done();
});
});
});
// run code after tests have completed
after(() => {
TestUtils.unMock();
});
describe('/my/route', () => {
it('should do something', (done) => {
return done();
});
});
});
Run Tests
APP_ENV=test ./node_modules/.bin/mocha
You could use ENV variables in other ways to set the dialect and connection parameters as well - the above is just an example based on what we have done with a lot of supporting code.
If you're not doing anything particularly complicated on the DB side, take a look at pg-mem:
https://swizec.com/blog/pg-mem-and-jest-for-smooth-integration-testing/
https://github.com/oguimbal/pg-mem
It's really cool in that it tests actual PG syntax and can pick up a bunch of errors that using a different DB or mock DB won't pick up. However, it's not a perfect implementation and missing a bunch of features (e.g. triggers, decent "not exists" handling, lots of functions) some of which are easy to work around with the hooks provided and some aren't.
For me, having the test DB initialized with the same schema initialization scripts as the real DB is a big win.

Babel not working with Mocha and starting Node server

I am running sailsjs, mocha, and babel on sails and mocha. When I run, my before function to start the sails app before running tests, I get this:
> PORT=9999 NODE_ENV=test mocha --recursive --compilers js:babel/register
lifting sails
1) "before all" hook
0 passing (757ms)
1 failing
1) "before all" hook:
Uncaught Error: only one instance of babel/polyfill is allowed
For the life of me, I can't figure out how to make mocha running babel and sails running babel at the same time work.
My before() code looks like this:
import Sails from 'sails'
// Global before hook
before(function (done) {
console.log('lifting sails')
// Lift Sails with test database
Sails.lift({
log: {
level: 'error'
},
models: {
connection: 'testMongoServer',
migrate: 'drop'
},
hooks: {
// sails-hook-babel: false
babel: false
}
}, function(err) {
if (err) {
return done(err);
}
// Anything else you need to set up
// ...
console.log('successfully lifted sails')
done();
});
});
I use sails-hook-babel and it works like a charm. Here to do it:
Install npm install sails-hook-babel --save-dev
Edit your bootstrap.js/ before function to load babel, i.e.
var Sails = require('sails'),
sails;
var options = {
loose : "all",
stage : 2,
ignore : null,
only : null,
extensions: null
};
global.babel = require("sails-hook-babel/node_modules/babel/register")(options);
before(function (done) {
Sails.lift({
//put your test only config here
}, function (err, server) {
sails = server;
if (err) return done(err);
// here you can load fixtures, etc.
done(err, sails);
});
});
after(function (done) {
// here you can clear fixtures, etc.
sails.lower(done);
});
Now you are able to use ES6 within your tests.
Here is the reference:
Babel issue at GitHub
My Blog, sorry it written in Bahasa Indonesia, use Google translate if you want to.

Resources