In AVA How can I import a variable from a test file to another test file - import

I am using AVA for testing. I have 2 files. In file1.spec.js, I am creating a user, and once the user is created a userId is generated and returned. I need this userId in file2.spec.js to test some other API calls specific to this user. How can I successfully export the userId created in file1.spec.js and import it into file2.spec.js? Thanks in advance!
I have tried the following:
file1.spec.js:
method: 'POST',
url: '/api/users',
data: setupFixture.postUsersAtLocation1
}).catch(err => { console.log(err.response.data); return err.response; });
if (result.status === 200) {
_int.userId = result.data.userId;
SCENARIO 1:
module.exports = {userId, userId1};
SCENARIO 2:
export {userId1};
export let userId = _int.userId;
file2.spec.js:
import test from 'ava';
import setup from './setup.spec.js';
const {userId, userId1} = setup;
var userIdA = userId;
var userId1A = userId1;
When I run this, it complains that file2.spec.js has an unexpected identifier (test) in import test from 'ava'. If I remove "import setup from './setup.spec.js';", and all after it, it no longer complains about test, but I never get the variables imported, either way.

Each test file is executed in a new worker process. Test files should not depend on another file having been executed first. Instead try and use a different database / table / IDs in each test file, then share setup code (if necessary) through helpers.

Related

Data return from axios cant be written to variable

I want to get an data attribute from my axios post and write it to an local variable to reuse it.
If i console.log it inside the axios .then, tha data is set, if i write it to my variable and want to use it after, it is empty.
export default {
data(){
return {
post:{},
projectId: '',
existingProjects: []
}
},
methods: {
addPost(){
//check if project exists else create
let uriProj = 'http://localhost:4000/projects/add';
this.axios.post(uriProj, {
projectName: this.post.project,
}).then(response => this.projectId = response.data.data);
console.log("project_id: "+this.projectId)
}
}
What am i doing wrong?
Another Question:
Is this the right way if i want to reuse the id in another method?
My Goal is to first create a project if it is not already in my db, then i want to reuse the id of the created or returned project model to create a new customer in my db, if the customer already has the project with the id of this project, it shouldnt be added, if it is a new one it should be added.
Has this to be done in multiple requests or is there a simple method for doing this?
I believe the issue you are seeing has to do with the asynchronous nature of network calls. When axios submits the post request it returns a Promise then the addPost function continues executing. So the projectId gets logged after it the initial value gets set, but before the network request completes. Everything inside the then() function executes once the network request has been completed so you can test by moving the console.log to be executed once the request is done. You could also output the value in the template so you can see it update {{ projectId }}
this.axios.post(uriProj, {
projectName: this.post.project,
}).then(response => {
this.projectId = response.data.data
console.log("project_id: "+this.projectId)
});
I would ideally recommend using the VueJS dev tools browser extension because it allows you to inspect the state of your Vue components without having to use console.log or add random echos to your template markup.
#jfadich is correct. I recommend using async/await instead of then, it's more intuitive to read.
async addPost(){
//check if project exists else create
let uriProj = 'http://localhost:4000/projects/add';
let resp = await this.axios.post(uriProj, {
projectName: this.post.project,
})
this.projectId = resp.data.data
console.log("project_id: "+this.projectId)
}

Is it possible to create a file with all my functions and read from from it in my specs?

I have some specs that are using the same functions, I would like to make one single file only for functions and read from this file while executing my scripts, would be that possible? if so.. how to do that?
During google searchers I found the "exports" to add in config file but didn't work (also I don't know how to call it from the config)
For example, I would like to add 2 functions in my config file (or separated file only for functions) and during any point of my execution, call it from the spec file:
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/');
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail(){
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
1 - How can I do that? (using "Suites" would be an option?)
2 - How to call them in my specs?
Thank you and have a good day!
As far as I know you cannot add utility functions that you want to use in your tests in the config file. The options in the config file are generally for setting up the testing environment.
You can however put your functions in a separate file and import that to use the functions. Below is an example of how to do that using js and Node's module exports, you can do something similar with ts using classes.
// utils.js
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/'); // nice Lenny face :)
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail() {
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
module.exports = {
loginAdminUserloginAdminUser: loginAdminUser,
accessHistoryViewDetail: accessHistoryViewDetail
}
Then in your spec file
import * as utils from './utils.js';
...
it('should ...', () => {
...
utils.accessHistoryViewDetail();
...
});
});
I hope that helps.

Jenkins: Active Choices Parameter + Groovy to build a list based on REST responde

I have a REST client that returns me a list of systems.
I need this list to be as a parameter for a jenkins job.
I think I need Actice Choices Parameter plugin with Groovy and HTTPBuilder in order to do that.
What do you guys think?
I did not find a way to install HTTPBuilder into Jenkins.
Is there any other way that you guys think it is possible?
I have run into the same problem trying to parse parameters via groovy script. Arun's answer did not work for me. However, I have managed to get it to work using the following:
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.URL
import java.net.URLConnection
import groovy.json.JsonSlurper
def choices = []
def url = new URL("some.data.url")
def conn = url.openConnection()
conn.setDoOutput(true)
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def results = new JsonSlurper().parseText(reader.getText());
reader.close()
results.each { data -> choices.push(data.field) }
return choices.sort()
First paste the JSON body snapshot output -or whatever your REST client is going to return. That'll help.
For ex: if it'll return a JSON object then you can use Active Choice Parameter's Groovy script step - OR Scriptler script (within the Active Choice Parameter plugin). PS: Scriptler script runs in the same JVM of Jenkins process so it has access to Jenkins/etc object for free. You don't need HTTPBuilder or anything. See the code sample below.
Assuming if your REST client is returning a JSON object and from that object if you want to list hostname of the system or some field name then replace the following variable with that and you'll get it listed while doing "Build with parameters" from Jenkins job's dashboard.
import groovy.json.JsonSlurper
//this will be your URL which will return something, tweak it if you want to pass parameters or username/password acc.
def SOME_URL = "https://koba.baby.com/some_url"
// now connect to the URL and create a connection variable 'conn'
def conn = SOME_URL.toURL().openConnection()
// create a list variable 'servernames'
def servernames = []
// if connection response was successful i.e. http protocol return code was 200, then do the following
if( conn.responseCode == 200 ) {
// get the results / output of the URL connection in a variable 'results'
def results = new JsonSlurper().parseText(conn.content.text)
// to see results variable output uncomment the next line
//println results
// now read each element in the 'results' variable and pick servername/somefield variable into the list variable 'servernames'
results.each { id, data -> servernames.push(data.someField_or_HostName) }
}
return servernames.sort().unique()
// return servernames.sort()

The requested built-in library is not available on Dartium

I am trying to make a very simple application that looks up values in a database by using polymer elements to get input.
My main polymer class looks like this:
library index;
import 'package:polymer/polymer.dart';
import 'lookup.dart';
import 'dart:html';
#CustomTag('auth-input')
class AuthInput extends PolymerElement {
#observable String username = '';
#observable String password = '';
AuthInput.created() : super.created();
void login(Event e, var detail, Node target)
{
int code = (e as KeyboardEvent).keyCode;
switch (code) {
case 13:
{
Database.lookUp(username, password);
break;
}
}
}
}
and a secondary database helper class looks like this:
library database;
import 'package:mongo_dart/mongo_dart.dart';
class Database {
static void lookUp(String username, String password) {
print("Trying to look up username: " + username + " and password: " + password);
DbCollection collection;
Db db = new Db("mongodb://127.0.0.1/main");
db.open();
collection = db.collection("auth_data");
var val = collection.findOne(where.eq("username", username));
print(val);
db.close();
}
}
I keep getting this error and I cannot think of a way around it:
The requested built-in library is not available on Dartium.'package:mongo_dart/mongo_dart.dart': error: line 6 pos 1: library handler failed
import 'dart:io';
The strange thing is, I don't want to use dart:io. The code works fine either running database processes or running polymer processes. I can't get them to work together. I don't see why this implementation of the code will not run.
The first line at https://pub.dartlang.org/packages/mongo_dart says
Server-side driver library for MongoDb implemented in pure Dart.
This means you can't use it in the browser. Your error message indicates the same. The code in the package uses dart:io and therefore can't be used in the browser.
Also mongodb://127.0.0.1/main is not an URL that can be used from within the browser.
You need a server application that does the DB access and provides an HTTP/WebSocket API to your browser client.

Is there a way to create and run a dynamic script from karma.conf.js

I'm using karma to run tests on an angularjs application.
There are a couple JavaScript functions that I would like to run at start-up, but they need to be dynamically created based on some system data. When running the app, this is handled with node.
Is there any way to create a script as a var and pass it to the files: [] rather than just using a pattern to load an existing file?
I can make this work by creating the file, saving it to disk then loading it normally, but that's messy.
You can create your own karma preprocessor script.
For a starting point use the following as example:
var fs = require('fs'),
path = require('path');
var createCustomPreprocessor = function (config, helper, logger) {
var log = logger.create('custom'),
// get here the configuration set in the karma.conf.js file
customConfig = config.customConfig || {};
// read more config here in case needed
...
// a preprocessor has to return a function that when completed will call
// the done callback with the preprocessed content
return function (content, file, done) {
log.debug('custom: processing "%s"\n', file.originalPath);
// your crazy code here
fs.writeFile(path.join(outputDirectory, name), ... , function (err) {
if (err) {
log.error(err);
}
done(content);
});
}
};
createCustomPreprocessor.$inject = ['config', 'helper', 'logger'];
module.exports = {
'preprocessor:custom': ['factory', createCustomPreprocessor]
};
Add a package.json with the dependencies and serve it as a module. ;)
For more examples have a look to more modules here: https://www.npmjs.org/search?q=karma%20preprocessor