Test function assignment inside a class method in Jest - javascript

I have a class in which i use strategy pattern it looks something like this:
class Foo {
constructor() {
this.doStuff = function() { /* not used really */ }
}
create(config) {
this.type = config.type;
// assign other variables to this
this.doStuff = StuffStrategy(config.type);
this.doStuff();
}
}
StuffStrategy is a function that returns other functions which use this context differently based on type.
function StuffStrategy(type) {
switch(type) {
case A: return StrategyA;
case B: return StrategyB;
// ...
}
}
function StrategyA() {
if(this.someVarInFoo) {
return 'a thing'
} else
return 'a different thing' + this.otherVarInFoo
}
I assign particular Strategy function inside create method.
Then I would like to test the create method if it calls doStuff.
describe('how create method works', () => {
const instance = new Foo();
const spy = jest.spyOn(instance, 'doStuff');
instance.create(config);
expect(spy).toBeCalled();
});
But when I try to make spy before calling instance.create then it refers to default method assigned in constructor, which gets replaced inside create.
If i make spy after calling instance.create then it will not pick the call
.
I tried to add .bind when defining this.doStuff:
this.doStuff = StuffStrategy(config.type).bind(this);
but it does not work either.
Is there something wrong with my setup?
How can I make this test case work?

You have to spyOn the strategy methods of your Foo class. So for every config.type you check then which strategy method has been called.
export class Foo {
constructor(){
this.doStuff = null;
}
create(config){
this.type = config.type;
// assign other variables to this
this.doStuff = StuffStrategy(config.type);
this.doStuff();
}
strategyA(){...}
strategyB(){...}
StuffStrategy(configtype) {
switch (configtype) {
case "A": return this.strategyA;
case "B": return this.strategyB;
}
}
}
import { Foo } from 'anyPlaceFoo/foo';
describe('Strategy', () => {
it('should call strategy A', () => {
const foo = new Foo();
// here you can spy on every strategy method.
jest.spyOn(foo, 'strategyA');
jest.spyOn(foo, 'strategyB');
foo.create({ type: 'A' });
// check if the selected one has been called but not the others
expect(foo.strategyA).toHaveBeenCalled();
expect(foo.strategyB).not.toHaveBeenCalled();
})
})

Related

How to mock a specific method of a class whilst keeping the implementation of all other methods with jest when the class instance isn't accessible?

Based on this question (How to mock instance methods of a class mocked with jest.mock?), how can a specific method be mocked whilst keeping the implementation of all other methods?
There's a similar question (Jest: How to mock one specific method of a class) but this only applies if the class instance is available outside it's calling class so this wouldn't work if the class instance was inside a constructor like in this question (How to mock a constructor instantiated class instance using jest?).
For example, the Logger class is mocked to have only method1 mocked but then method2 is missing, resulting in an error:
// Logger.ts
export default Logger() {
constructor() {}
method1() {
return 'method1';
}
method2() {
return 'method2';
}
}
// Logger.test.ts
import Logger from './Logger';
jest.mock("./Logger", () => {
return {
default: class mockLogger {
method1() {
return 'mocked';
}
},
__esModule: true,
};
});
describe("Logger", () => {
it("calls logger.method1() & logger.method2 on instantiation where only method1 is mocked", () => {
const logger = new Logger(); // Assume this is called in the constructor of another object.
expect(logger.method1()).toBe('mocked');
expect(logger.method2()).toBe('method2'); // TypeError: logger.method2 is not a function.
});
});
One solution is to extend the Logger class but this results in an undefined error as the Logger is already mocked:
// ...
jest.mock("./Logger", () => {
return {
default: class mockLogger extends Logger {
override method1() {
return 'mocked';
}
},
__esModule: true,
};
});
// ...
expect(logger.method2()).toBe('method2'); // TypeError: Cannot read property 'default' of undefined
Therefore, what could be the correct way to mock only method1 but keep method2's original implementation?
You can use jest.spyOn and provide a mock implementation for method1.
// Logger.test.ts
import Logger from './Logger';
jest.spyOn(Logger.prototype, "method1").mockImplementation(() => "mocked")
describe("Logger", () => {
it("calls method1 & method2 but only method1 is mocked", () => {
const l = new Logger();
expect(l.method1()).toBe("mocked");
expect(l.method2()).toBe("method2");
})
})
But in case you have many methods and you want to mock each one of them except one single method, then you can get the original implementation of this one single method using jest.requireActual.
// Logger.test.ts
import Logger from "./Logger";
const mockMethod1 = jest.fn().mockReturnValue("mocked");
const mockMethod3 = jest.fn().mockReturnValue("mocked");
const mockMethod4 = jest.fn().mockReturnValue("mocked");
const mockMethod5 = jest.fn().mockReturnValue("mocked");
jest.mock("./Logger", () =>
jest.fn().mockImplementation(() => ({
method1: mockMethod1,
method2: jest.requireActual("./Logger").default.prototype.method2,
method3: mockMethod3,
method4: mockMethod4,
method5: mockMethod5,
}))
);
describe("Logger", () => {
it("calls all methods but only method1 is mocked", () => {
const l = new Logger();
expect(l.method1()).toBe("mocked");
expect(l.method2()).toBe("method2");
expect(l.method3()).toBe("mocked");
expect(l.method4()).toBe("mocked");
expect(l.method5()).toBe("mocked");
});
});
Note: You don't need to define an ES6 class for mocking, a constructor function also just works fine because ES6 classes are actually just syntactic sugar for constructor functions.
Mocking the prototype works:
describe("Logger", () => {
it("calls logger.method1() & logger.method2 on instantiation where only method1 is mocked", () => {
Logger.prototype.method1 = jest.fn(() => 'mocked');
const logger = new Logger();
expect(logger.method1()).toBe('mocked');
expect(logger.method2()).toBe('method2');
});
});
However, I'm not sure if this is the correct way to mock a specific method when the class instance isn't accessible so I'll leave the question open for while in case there are better solutions.

Error when delegating class method in ES6

I have this UseCase class:
class UseCase {
constructor(repository) {
this.repository = repository;
}
execute() {
//do stuff
}
}
module.exports = UseCase;
and this Service class:
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
}
doWork = this.useCase.execute;
}
module.exports = Service;
What I want is delegate service.doWork() call to useCase.execute(), but when I execute it, I get this error:
TypeError: Cannot read property 'execute' of undefined
However, if I change my Service code to this:
class Service {
constructor(repository) {
this.repository = repository;
}
doWork = new UseCase(this.repository).execute;
}
module.exports = Service;
it works properly! Why is that? What am I missing?
Class fields run as soon after the constructor they can, right after any super calls, if any. Your code is equivalent to:
class Service {
constructor(repository) {
this.doWork = this.useCase.execute;
this.useCase = new UseCase(repository);
}
}
It's not defined in time.
Put doWork in the constructor instead, after the assignment to useCase.
You also need to make sure that .execute is called with the proper calling context - just passing this.useCase.execute loses the calling context of useCase.
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
this.doWork = () => this.useCase.execute();
}
}
You could also use a class field which calls .execute when called:
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
}
doWork = () => this.useCase.execute();
}

"new self()" equivalent in Javascript

I have a class like the following:
const Module = {
Example: class {
constructor(a) {
this.a = a;
}
static fromString(s) {
// parsing code
return new Module.Example(a);
}
}
}
This works so far, but accessing the current class constructor via the global name Module.Example is kind of ugly and prone to breaking.
In PHP, I would use new self() or new static() here to reference the class that the static method is defined in. Is there something like this in Javascript that doesn't depend on the global scope?
You can just use this inside the static method. It will refer to the class itself instead of an instance, so you can just instantiate it from there.
If you need to access the constructor from an instance function, you can use this.constructor to get the constructor without specifying its name.
Here's how:
const Module = {
Example: class Example {
constructor(a) {
this.a = a;
}
static fromString(s) {
// parsing code
return new this(s);
}
copy() {
return new this.constructor(this.a);
}
}
}
const mod = Module.Example.fromString('my str');
console.log(mod) // => { "a": "my str"
console.log(mod.copy()) // => { "a": "my str" }
console.log('eq 1', mod === mod) // => true
console.log('eq 2', mod === mod.copy()) // => false

Run chained method before anything in constructor?

I have this simple class:
class Foo {
constructor() {
this.init();
return this;
}
init() {
this.onInit();
}
onInit(callback) {
this.onInit = () => callback();
return this;
}
}
new Foo().onInit(() => console.log('baz'));
It's obviously flawed, because it will call init before the onInit method is able to define the onInit property/callback.
How can I make this work without change the interface?
How can I make this work without change the interface?
You can't, the interface is inherently flawed. That's really the answer to your question.
Continuing, though, with "what can I do instead":
If you need to have a callback called during initialization, you need to pass it to the constructor, not separately to the onInit method.
class Foo {
constructor(callback) {
this.onInit = () => {
callback(); // Call the callback
return this; // Chaining seemed important in your code, so...
};
// Note: Constructors don't return anything
}
}
new Foo(() => console.log('baz'));
In a comment you've said:
I see your point, the fact is that my library is new Something().onCreate().onUpdate()
It sounds like you might want to adopt the builder pattern instead:
class Foo {
constructor(callbacks) {
// ...use the callbacks here...
}
// ...
}
Foo.Builder = class {
constructor() {
this.callbacks = {};
}
onCreate(callback) {
this.callbacks.onCreate = callback;
}
onUpdate(callback) {
this.callbacks.onUpdate = callback;
}
// ...
build() {
// Validity checks here, do we have all necessary callbacks?
// Then:
return new Foo(this.callbacks);
}
};
let f = new Foo.Builder().onCreate(() => { /*...*/}).onUpdate(() => { /*... */}).build();
...although to be fair, a lot of the advantages (though not all) of the builder pattern can be realized in JavaScript by just passing an object into constructor directly and doing your validation there, e.g.:
let f = new Foo({
onCreate: () => { /*...*/},
onUpdate: () => { /*...*/}
});
Assuming that onInit is supposed to be some sort of hook to be called synchronously whenever an object is instantiated, you can't solve this on the instance level.
You can make onInit a static function, like so:
class Foo {
constructor() {
// whatever
Foo.onInit();
}
static onInit() {} // empty default
}
Foo.onInit = () => console.log('baz'); // Override default with your own function
const f = new Foo();
const f2 = new Foo();

Generic reading of arguments from multiple constructor calls

Follow-up question to Read arguments from constructor call:
The accepted solution allows me to get arguments passed into a constructor by defining a wrapper class that captures and exposes the arguments, but this leaves me with the problem of having n wrappers for n constructors.
Is there a way to have 1 function/wrapper/whatever that could work for any number of constructors?
I'll reiterate that I'm pursing this technique specifically to test Webpack plugin configuration, and I'd like to avoid having a separate wrapper for each plugin that I need to test.
Looking for something along the lines of
// ------------------------------------------------------------ a wrapper function?
const someWrapper = () => { /* ... */ }
const plugin1 = new Plugin({ a: 'value' })
const plugin2 = new Plugin2(arg1, arg2, { b: 'anotherValue '})
someWrapper(plugin1).args === [{ a: 'value' }]
someWrapper(plugin2).args === [arg1, arg2, { b: 'anotherValue' }]
// --------------------------------------------------------------- a wrapper class?
class Wrapper { /* ... */ }
const plugin1 = new Wrapper(Plugin, [{ a: 'value' }])
const plugin2 = new Wrapper(Plugin2, [arg1, arg2, { b: 'anotherValue '}])
plugin1.args === [{ a: 'value' }]
plugin2.args === [arg1, arg2, { b: 'anotherValue '}]
// problem with above is the wrapper is being passed to Webpack, not the underlying
// plugin; not sure yet if this would cause webpack to break or not actually
// execute the plugin as intended with a vanilla config
// ---------------------------------------------------------------- something else?
Yes, you can create generic wrapper which will add args property to instance of any passed constructor:
class Plugin {
constructor (arg1, arg2) {
this.arg1 = arg1
this.arg2 = arg2
}
}
function wrapper(initial) {
// Rewrite initial constructor with our function
return function decoratedContructor(...args) {
// Create instance of initial object
const decorated = new initial(...args)
// Add some additional properties, methods
decorated.args = [...args]
// Return instantiated and modified object
return decorated
}
}
const decoratedPlugin = wrapper(Plugin)
const plugin = new decoratedPlugin('argument', { 'argument2': 1 })
console.log(plugin.args)
FYI: it's not safe to add properties without some prefix. Consider adding __ or something like this to your property, because you can accidentally rewrite some inner object property.
I was able to get this working with a modification to #guest271314's suggestion, namely, you need to pass ...initArgs to super(), otherwise webpack will fail with a TypeError: Cannot read property '...' of undefined.
Also took #terales's point into account about making sure to prefix my additional properties.
const exposeConstructorArgs = (Plugin, ...args) => {
const ExposedPlugin = class extends Plugin {
constructor(...initArgs) {
super(...initArgs);
this.__initArgs__ = initArgs;
}
get __initArgs() {
return this.__initArgs__;
}
};
return Reflect.construct(ExposedPlugin, args);
};
// ...
const dllPlugin = exposeConstructorArgs(webpack.DllPlugin, {
name: '[name]',
path: path.join(buildDir, '[name].json'),
});
// ...
const pluginConfig = dllPlugin.__initArgs[0];
expect(pluginConfig.name).toEqual('[name]');
You can use a generic function where class expression is used within function body. Pass reference to the class or constructor and parameters expected to be arguments within the instance to the function call.
function Plugin() {}
function Plugin2() {}
function PluginWrapper(pluginRef, ...args) {
let MyPlugin = class extends pluginRef {
constructor() {
super();
this.args = [...arguments];
}
getArgs() {
return this.args;
}
}
return Reflect.construct(MyPlugin, args);
};
const anInstance = PluginWrapper(Plugin, {
a: 'path'
});
console.log(anInstance.getArgs(), anInstance instanceof Plugin);
const aSecondInstance = PluginWrapper(Plugin2, "arg1", "arg2", {
b: 'anotherPath'
});
console.log(aSecondInstance.getArgs(), aSecondInstance instanceof Plugin2);

Categories

Resources