XMLSerializer is undefined in jest test - xml-parsing

I was using XMLSerializer class in one of NODE package class method. When writing unit test case using jest it threw error of XMLSerializer is not undefined. As this is native to browser, there can not be any package.
Even I searched online, found few suggestions of using a new jsdom and creating a prototype of XMLSerializer.
No proper solution is found even no posts at SO.

I've currently used a wrapped for XMLSerializer as below (typescript code):
export default class XmlSerializerWrapper {
private serializer: XMLSerializer;
constructor() {
this.serializer = new XMLSerializer();
}
public serializeToString(doc: Document) {
return this.serializer.serializeToString(doc);
}
}
It works fine.

Had the same issue today and came upon this post. My approach:
describe('MyXmlDocument', () => {
global.XMLSerializer = function() {
return {
serializeToString : jest.fn(x => x)
};
}
... your tests here
});
My code only needs the serializeToString() method, so that's the only one mocked.

Related

Jenkins scripted Pipeline: How to apply #NonCPS annotation in this specific case

I am working on a scripted Jenkins-Pipeline that needs to write a String with a certain encoding to a file as in the following example:
class Logger implements Closeable {
private final PrintWriter writer
[...]
Logger() {
FileWriter fw = new FileWriter(file, true)
BufferedWriter bw = new BufferedWriter(fw)
this.writer = new PrintWriter(bw)
}
def log(String msg) {
try {
writer.println(msg)
[...]
} catch (e) {
[...]
}
}
}
The above code doesn't work since PrintWriter ist not serializable so I know I got to prevent some of the code from being CPS-transformed. I don't have an idea on how to do so, though, since as far as I know the #NonCPS annotation can only be applied to methods.
I know that one solution would be to move all output-related code to log(msg) and annotate the method but this way I would have to create a new writer every time the method gets called.
Does someone have an idea on how I could fix my code instead?
Thanks in advance!
Here is a way to make this work using a log function that is defined in a shared library in vars\log.groovy:
import java.io.FileWriter
import java.io.BufferedWriter
import java.io.PrintWriter
// The annotated variable will become a private field of the script class.
#groovy.transform.Field
PrintWriter writer = null
void call( String msg ) {
if( ! writer ) {
def fw = new FileWriter(file, true)
def bw = new BufferedWriter(fw)
writer = new PrintWriter(bw)
}
try {
writer.println(msg)
[...]
} catch (e) {
[...]
}
}
After all, scripts in the vars folder are instanciated as singleton classes, which is perfectly suited for a logger. This works even without #NonCPS annotation.
Usage in pipeline is as simple as:
log 'some message'

How to get a "constructor" or a factory without reflection in Flutter

As Flutter has no reflection (due to tree shaking) I need to find a way to create Objects of a specific Type at runtime and I would strongly prefere to do it without code generation. So I think the best way to register a Type to be created like this would be the following:
class Test with Bindable {
static Test create() {
return new Test();
}
}
registerTest() {
registerType<Test>("test", Test.create);
}
void registerType<T extends Bindable>(String s, T Function() create) {}
Any other ideas?

Code coverage in Haxe

Let's assume I have a Unit Test like this:
import haxe.unit.TestRunner;
import haxe.unit.TestCase;
class MyTests extends haxe.unit.TestCase {
public function testSomething():Void {
// ...
}
public function testSomethingElse():Void {
// ...
}
public static function main():Void {
var tr = new TestRunner();
tr.add(new MyTests());
tr.run();
}
}
Now, after running my tests, I want to analyse, which lines of my code got tested and which not (code coverage) ... or at least see which functions of a certain class have been executed during test run (just to prevent that I do not have forgotten to test any functions). How can I do that?
MCover is currently the only real option at the moment. There is also one called coverme, but it’s not meant for public use yet.

How can I use Reflection (Mirrors) to access the method names in a Dart Class?

I need to "fetch" the methods in a Dart Class.
How can I do this?
And I want to be able to call the methods.
May I see an example?
Here's an easy copy-pasteable code sample:
import 'dart:mirrors';
import 'dart:io';
main() {
var im = reflect(new File('test')); // Retrieve the InstanceMirror of some class instance.
im.type.methods.values.forEach((MethodMirror method) => print(method.simpleName));
}
Output is:
existsSync
_delete
exists
directory
_getDecodedLines
readAsTextSync
readAsBytesSync
readAsLinesSync
_directory
throwIfError
lastModifiedSync
readAsLines
open
_ensureFileService
deleteSync
delete
_exists
length
openInputStream
create
_create
readAsText
_openStdioSync
openOutputStream
_fullPath
_lastModified
fullPathSync
readAsBytes
lastModified
_openStdio
_open
openSync
lengthSync
directorySync
fullPath
createSync
_lengthFromName
Here is a basic example:
(Note: You will want to have a (very) up to date version of the SDK for this, this was done in Dart Editor version 0.2.1_r14167, Dart SDK version 0.2.1.2_r14167 Nov 2, 2012)
My most sincere Thanks to Gilad of the Google Dart Team for providing this example!
#import('dart:mirrors');
class MyClass {
String _test;
String get test => _test;
set test(String paramVal) => _test = paramVal;
void my_method() {
}
void print_test(){
print("test string is: ${_test}");
}
MyClass(String test) {
_test = test;
}
}
main() {
MyClass myClass = new MyClass("Make my day, PUNK.");
myClass.print_test();
//ClassMirror myClassMirror = reflect(myClass).type;
InstanceMirror myClassInstanceMirror = reflect(myClass);
ClassMirror MyClassMirror = myClassInstanceMirror.type;
Map<String, MethodMirror> map = MyClassMirror.methods;
print("map = ${map}");
map.values.forEach( (MethodMirror mm){
myClassInstanceMirror.invoke(mm.simpleName,[]);
});
}
Concerning Reflection I have just written a couple of "Helper Functions" for fetching a LIST of the method names (not a Map) and invoking the method... all I can say for sure is that it works right now. There are likely technical reasons for not doing it this way - but in my case this does not run in a complex environment. However, I do think they nicely mask over a lot of details that not everybody is going to want to deal with.
Here's a functioning demonstration with and without the Helper functions:
#import('dart:mirrors');
class MyClass {
String _test;
String get test => _test;
set test(String paramVal) => _test = paramVal;
void my_method1(){print("in method1");}
void my_method2(){print("in method2");}
void print_test(){
print("test string is: ${_test}");
}
MyClass(String test) {
_test = test;
}
}
//Helper Methods
InstanceMirror hMr;
List REFLECT_methods(Object myClass) {hMr=reflect(myClass);return(hMr.type.methods.values);}
REFLECT_invoke(MethodMirror mm){hMr.invoke(mm.simpleName, []);}
main() {
MyClass myClass = new MyClass("Make my day, PUNK.");
print("\n=======Using Raw Reflection================");
InstanceMirror myClassInstanceMirror = reflect(myClass);
ClassMirror MyClassMirror = myClassInstanceMirror.type;
Map<String, MethodMirror> map1 = MyClassMirror.methods;
map1.values.forEach( (MethodMirror mm){
myClassInstanceMirror.invoke(mm.simpleName,[]);
});
print("\n==========Using Helper functions=============");
List list2 = REFLECT_methods(myClass);
list2.forEach((method){
REFLECT_invoke(method);
});
}

How to create ObjectQuery for testing EF4 'Include' method

We are using EF4 and creating test cases for DAL layer (DAL layer is having linq query). We are using TypeMock as mocking framework. For testing, we are creating Fakecontext of ObjectContext and mocking CreateObjectSet method as follows:
Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable());
The above is working fine. The issue is when we are trying to include related tables using 'Include'. We have extended the include method as follows:
public static IQueryable<T> Include<T>(this IQueryable<T> source, Expression<Func<T>> property)
{
var objectQuery = source as ObjectQuery<T>;
if (objectQuery != null)
{
var propertyPath = GetPropertyPath(property);
return objectQuery.Include(propertyPath);
}
return source;
}
So what happen is, in the above Include method the source type should be ObjectQuery<T>. But as we have mocked CreateObjectSet, source type in Include method is of Collection.Generic.List type. Kindly let us know how should we mock in the above case. Your timely help will be highly appreciable. Thanks
Object Services can be difficult to use when writing unit test. Unfortunately, there is not a good interface to mock for ObjectQuery<T> as you have found out. To handle this scenario I have created a wrapper class following the Repository pattern to encapsulate my ObjectContext and created a wrapper class to encapsulate ObjectQuery<T>:
public interface IMyObjectQuery<T> : IOrderedQueryable<T>
{
IMyObjectQuery<T> Include(string path);
}
public class MyObjectQuery<T> : IMyObjectQuery<T>
{
private ObjectQuery<T> _query;
public MyObjectQuery(ObjectQuery<T> query)
{
_query = query;
}
IMyObjectQuery<T> Include(string path)
{
//There is probably a better way to do this
//but you get the idea
return new MyObjectQuery(_query.Include(path));
}
//Implement IQueryable, IEnumerable...
}
And then it is a matter of implementing a Repository wrapper for your ObjectContext. Here is a link to get you started.
Add something like this:
public class MyRepository : IMyRespository
{
...
public IMyObjectQuery<T> CreateQuery<T>()
{
return new MyObjectQuery(_context.CreateQuery<T>());
}
...
}
This is probably not the simple solution that you were looking for, as it is not a trivial task. I think you will find that if you don't you will continue to encounter difficulty writing tests.

Resources