I'm trying to test function calls inside the class to make sure they're called, but I can't seem to figure out how to do that with Jest.
Automatic mocks don't work, and neither does calling jest.mock with the module factory param.
This is the class in question, and I want to test that calling play() calls playSoundFile().
class SoundPlayer {
constructor() {
this.foo = 'bar';
}
playSoundFile(fileName) {
console.log('Playing sound file ' + fileName);
}
play() {
this.playSoundFile('song.mp3');
}
}
module.exports = SoundPlayer;
This is the test file:
const SoundPlayer = require('../sound-player');
jest.mock('../sound-player');
it('test', () => {
const soundPlayerConsumer = new SoundPlayer();
const coolSoundFileName = 'song.mp3';
soundPlayerConsumer.play();
const mockPlaySoundFile = SoundPlayer.mock.instances[0].playSoundFile;
expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);
});
mockPlaySoundFile.mock.calls is empty, and it errors out because of that.
I propose you don't mock any internal method. Instead you can mock any external dependency and call methods supposed to be public. Then you run assertions against what public(supposed to be called outside) methods return and also check mocks(mocked external dependencies) for being/not being called.
In this particular example there is just console.log:
console.log = jest.fn();
const soundPlayerConsumer = new SoundPlayer();
soundPlayerConsumer.play();
expect(console.log).toHaveBeenCalledTimes(1);
expect(console.log).toHaveBeenCalledWith('Playing sound file song.mp3');
In more real-world scenario it may need you to mock document or even use jsdom to mock <audio /> HTML element. But approach would be the same.
If I don't mock the entire class and just spy on the function, it works. However this doesn't get around testing intensive functions, e.g. calls to the database.
const SoundPlayer = require('../sound-player');
it('test', () => {
const soundPlayerConsumer = new SoundPlayer();
const playSpy = jest.fn();
soundPlayerConsumer.playSoundFile = fileName => playSpy(fileName);
soundPlayerConsumer.play();
expect(playSpy).toHaveBeenCalledWith('song.mp3');
});
Related
I have the following module in my codebase:
const getSomething = () => new SomeThirdPartyCall();
const doSomethingElse = () => {
const foo = getSomething();
foo.bar();
};
const someService = { getSomething, doSomethingElse };
export { somethingService };
The way export works is to preserve service name in the calls, i.e. somethingService.doSomethingElse call will always be consistent across the app.
Now I'm trying to test doSomethingElse method and mocking getSomething to avoid calling 3rd party lib but it just doesn't work and still calls that 3rd party. What I tried:
somethingService.doSomethingElse = jest.fn().mockReturnValueOnce(); // doesnt work
const doSomethingElseMock = jest.spyOn(somethingService, 'doSomethingElse');
doSomethingElseMock.mockReturnValueOnce() // doesnt work
doSomethingElseMock.mockImplementationOnce() // doesnt work
What did I miss and why it's not mocking the function?
I'm trying to stub a function using sinon. The function has the following signature
export function getIndexDocument(
svc: MetaHTTPService | ServiceConfig
): MetaPromise<RepoResponseResult<IndexDocument>> {
Is this the right way to sub it
sandbox.stub(getIndexDocument).resolves({} as RepoResponseResult)
I tried that but it returns an error.
Here's how this function is called.
I have a class called AssetsController with the following functions
public async exploreIndexDocument(): Promise<Asset | undefined> {
// it makes an HTTP request and returns a promise that resolves with the following info { repoId: "", assetId: "" }
const {
result: { assignedDirectories }
} = await getIndexDocument(this.serviceConfig).catch(err => {
throw new Error(`Bad repsonse`);
});
return {
repoId: result.repoId;
assetId: result.assetId
}
}
public async function copyAsset(asset) {
const res = await this.exploreIndexDocument();
const repoId = res.repoId;
return asset.copy(repoId);
}
I'm trying to test the function copyAsset, but it calls exploreIndexDocument which calls getIndexDocument. getIndexDocument is imported at the top of the file and lives in the module #ma/http.
getIndexDocument makes an HTTP request.
How can I test copyAsset given that it calls getIndexDocument which makes an HTTP request?
According to the docs, you can't stub an existing function.
You can:
// Create an anonymous sstub function
var stub = sinon.stub();
// Replaces object.method with a stub function. An exception is thrown
// if the property is not already a function.
var stub = sinon.stub(object, "method");
// Stubs all the object’s methods.
var stub = sinon.stub(obj);
What you can't do is stub just a function like:
var stub = sinon.stub(myFunctionHere);
This makes sense because if all you have is a reference to a function, then you can just create a new function to use instead, and then pass that into where ever your test needs it to go.
I think you just want:
const myStub = sandbox.stub().resolves({} as RepoResponseResult)
In your update it sounds like you want to put the stub on the AssetsController class. See this answer for more info on that, but in this case I think you want:
const myStub = sandbox
.stub(AssetsController.prototype, 'exploreIndexDocument')
.resolves({} as RepoResponseResult)
Now anytime an instance of AssetsController calls its exploreIndexDocument method, the stub should be used instead.
Playground
I think most of your problems can be solved by revisiting your architecture. For example, instead of creating an explicit dependency on getIndexDocument within your AssetController class you can simply inject it in. This will allow you to swap implementations depending on the context.
type IndexDocumentProvider = (svc: MetaHTTPService | ServiceConfig) => MetaPromise<RepoResponseResult<IndexDocument>>;
interface AssetControllerOptions {
indexDocumentProvider: IndexDocumentProvider
}
class AssetController {
private _getIndexDocument: IndexDocumentProvider;
public constructor(options: AssetControllerOptions) {
this._getIndexDocument = options.indexDocumentProvider;
}
}
Then you can use this._getIndexDocument wherever and not worry about how to make the original implementation behave like you want in your tests. You can simply provide an implementation that does whatever you'd like.
describe('copyAsset', () => {
it('fails on index document error.', () => {
const controller = new AssetController({
indexDocumentProvider: () => Promise.reject(new Error(':('));
});
....
});
it('copies asset using repo id.', () => {
const controller = new AssetController({
indexDocumentProvider: () => Promise.resolve({ repoId: "420" })
});
...
});
});
You can obviously use stubs instead of just functions or whatever if you need something fancy.
Above we removed an explicit dependency to an implementation and instead replaced it with a contract that must be provided to the controller. The is typically called Inversion of Control and Dependency Injection
So I am writing a test case for one of my function where I am making a call to another function of a library and I am trying to mock that function(saveCall), here is the sample code:
import { Call } from './somefolder/call';
class Demo {
var testIt = (params: any) => {
---- // Some other code
let call = new Call(params);
call.saveCall();
---- // Some other code
}
return {testIt: testIt};
}
And here is how I am writing unit test case for the same:
import { Call } from './somefolder/call';
var demo = new Demo();
test("Test it", () => {
let call = new Call({} as any);
let spyIt = jest.spyOn(call, 'saveCall').mockImplementation(()=>{console.log('here')});
demo.testIt();
expect(spyIt).toHaveBeenCalled(); // Throws error expect(jest.fn()).toHaveBeenCalled()
});
I am getting expect(jest.fn()).toHaveBeenCalled() error in expect, Now I feel I am getting error because the instance of call object in test file is different from what I have in Demo class and that is the reason spyOn doesn't know that whether the function has been called or not. I did try with mocking the entire Call.ts file but getting the same error.
Now my question is how can I create a mock and sucessfully test whether saveCall() has been called. Please note that I cannot change the implementation of testIt function.
Using jest.mock helper to mock Call class and assert on instance of the mocked class.
import { Call } from './somefolder/call';
import { Demo } from './Demo';
jest.mock('./somefolder/call'); // mock all named export items
describe("Demo", () => {
let demo: Demo;
let CallMocked: jest.Mock<Call>; // define type for mocked class
beforeEach(() => {
CallMocked = Call as any; // Actually, now Call is a mocked class
demo = new Demo();
});
test("Test it", () => {
demo.testIt();
expect(CallMocked.mock.instances[0].saveCall).toHaveBeenCalled(); // assert for mock instance
});
})
I'm trying to use Jest manual mock to mock the behaviour of a package X used
in a project.
The usage of package X within the the actual application code is like so:
// Real.js
import X from '../lib/X.js';
export default class App {
...
execute() {
const x = new X(); // creating a new instance of X
x.doSomething(); // calling someThing() of X
}
...
}
my Jest manual mock to mimic the behaviour of X looks like:
global.__test__X = () => ({
doSomething: jest.fn(async () => console.log('mocked async do something')),
id: (Math.random() * 1000) % 10,
});
module.exports = global.__test__X;
In my test i'm trying to see how many times X was called and with what parameters
using the blow code:
jest.mock('../X');
import Real from '../Real';
const X = require('../X');
describe('Testing...', async () => {
it('DoSomething should print mocked console statement', async () => {
Real.execute(); // this would internally call X.doSomething()
const x = new X();
console.log(x.doSomething.mock.calls); // gives []
});
});
Using above, I'm trying to check how many times X was called but can't figure out what
i'm doing wrong since mock.calls is always []. Note that the mock is getting
executed as i can see mocked async do something.
There's a complete explanation for doing this with jest.mock('./SomeClass'); that applies to this question. "ES6 class, Automatic mock" .
let's get started.
// ./lib/X.js
export default class X {
constructor () {
this.id = '1234567890';
}
doSomething = () => {
return 'Original X';
}
}
Note, the above code has never been called during the test.
This is the resource we want to test, what I mean is, in this class create objects by the class or module that is mocked. We want to make a fake version instead of the original.
// Real.js
import X from './lib/X.js';
export default class App {
constructor() {
this.x = new X(); // creating a new instance of X
}
execute = () => {
this.x.doSomething(); // calling someThing() of X
}
}
Accepts a function that should be used as the implementation of the mock. So what we will do is using manual mocks ( __ mocks __ folder) to mock ES6 classes.
// ./__mocks__/lib/X.js
module.exports = jest.fn().mockImplementation(() => {
return {
doSomething: jest.fn(() => 'Mocking Original X'),
id: (Math.random() * 1000) % 10
}
});
When we import './lib/X.js' on our test file, Now, in order to test this method without actually hitting the library (and thus creating slow and fragile tests), we immediately use the mock the './lib/X.js' module.
// Real.test.js
import X from './lib/X.js';
import Real from './Real';
jest.mock('./lib/X.js'); // // X module is now a mock constructor
describe('Testing', async () => {
beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
X.mockClear();
});
it('DoSomething should print mocked correct statement', async () => {
// Ensure our mockClear() is clearing out previous calls to the constructor
expect(X).not.toHaveBeenCalled();
const real = new Real();
expect(X).toHaveBeenCalledTimes(1); // Constructor has been called X.js
real.execute();
// mock.instances is available with automatic mocks:
const mockXInstance = X.mock.instances[0];
const mockDoSomething = mockXInstance.doSomething;
expect(mockDoSomething).toHaveBeenCalledTimes(1);
expect(mockDoSomething.mock.calls[0][0]).toEqual('Mocking Original X');
});
});
maybe this is not enough to answer, at least this explains how mock works in similar cases
I'm trying to mock an ES6 class with a constructor that receives parameters, and then mock different class functions on the class to continue with testing, using Jest.
Problem is I can't find any documents on how to approach this problem. I've already seen this post, but it doesn't resolve my problem, because the OP in fact didn't even need to mock the class! The other answer in that post also doesn't elaborate at all, doesn't point to any documentation online and will not lead to reproduceable knowledge, since it's just a block of code.
So say I have the following class:
//socket.js;
module.exports = class Socket extends EventEmitter {
constructor(id, password) {
super();
this.id = id;
this.password = password;
this.state = constants.socket.INITIALIZING;
}
connect() {
// Well this connects and so on...
}
};
//__tests__/socket.js
jest.mock('./../socket');
const Socket = require('./../socket');
const socket = new Socket(1, 'password');
expect(Socket).toHaveBeenCalledTimes(1);
socket.connect()
expect(Socket.mock.calls[0][1]).toBe(1);
expect(Socket.mock.calls[0][2]).toBe('password');
As obvious, the way I'm trying to mock Socket and the class function connect on it is wrong, but I can't find the right way to do so.
Please explain, in your answer, the logical steps you make to mock this and why each of them is necessary + provide external links to Jest official docs if possible!
Thanks for the help!
Update:
All this info and more has now been added to the Jest docs in a new guide, "ES6 Class Mocks."
Full disclosure: I wrote it. :-)
The key to mocking ES6 classes is knowing that an ES6 class is a function. Therefore, the mock must also be a function.
Call jest.mock('./mocked-class.js');, and also import './mocked-class.js'.
For any class methods you want to track calls to, create a variable that points to a mock function, like this: const mockedMethod = jest.fn();. Use those in the next step.
Call MockedClass.mockImplementation(). Pass in an arrow function that returns an object containing any mocked methods, each set to its own mock function (created in step 2).
The same thing can be done using manual mocks (__mocks__ folder) to mock ES6 classes. In this case, the exported mock is created by calling jest.fn().mockImplementation(), with the same argument described in (3) above. This creates a mock function. In this case, you'll also need to export any mocked methods you want to spy on.
The same thing can be done by calling jest.mock('mocked-class.js', factoryFunction), where factoryFunction is again the same argument passed in 3 and 4 above.
An example is worth a thousand words, so here's the code.
Also, there's a repo demonstrating all of this, here:
https://github.com/jonathan-stone/jest-es6-classes-demo/tree/mocks-working
First, for your code
if you were to add the following setup code, your tests should pass:
const connectMock = jest.fn(); // Lets you check if `connect()` was called, if you want
Socket.mockImplementation(() => {
return {
connect: connectMock
};
});
(Note, in your code: Socket.mock.calls[0][1] should be [0][0], and [0][2] should be [0][1]. )
Next, a contrived example
with some explanation inline.
mocked-class.js. Note, this code is never called during the test.
export default class MockedClass {
constructor() {
console.log('Constructed');
}
mockedMethod() {
console.log('Called mockedMethod');
}
}
mocked-class-consumer.js. This class creates an object using the mocked class. We want it to create a mocked version instead of the real thing.
import MockedClass from './mocked-class';
export default class MockedClassConsumer {
constructor() {
this.mockedClassInstance = new MockedClass('yo');
this.mockedClassInstance.mockedMethod('bro');
}
}
mocked-class-consumer.test.js - the test:
import MockedClassConsumer from './mocked-class-consumer';
import MockedClass from './mocked-class';
jest.mock('./mocked-class'); // Mocks the function that creates the class; replaces it with a function that returns undefined.
// console.log(MockedClass()); // logs 'undefined'
let mockedClassConsumer;
const mockedMethodImpl = jest.fn();
beforeAll(() => {
MockedClass.mockImplementation(() => {
// Replace the class-creation method with this mock version.
return {
mockedMethod: mockedMethodImpl // Populate the method with a reference to a mock created with jest.fn().
};
});
});
beforeEach(() => {
MockedClass.mockClear();
mockedMethodImpl.mockClear();
});
it('The MockedClassConsumer instance can be created', () => {
const mockedClassConsumer = new MockedClassConsumer();
// console.log(MockedClass()); // logs a jest-created object with a mockedMethod: property, because the mockImplementation has been set now.
expect(mockedClassConsumer).toBeTruthy();
});
it('We can check if the consumer called the class constructor', () => {
expect(MockedClass).not.toHaveBeenCalled(); // Ensure our mockClear() is clearing out previous calls to the constructor
const mockedClassConsumer = new MockedClassConsumer();
expect(MockedClass).toHaveBeenCalled(); // Constructor has been called
expect(MockedClass.mock.calls[0][0]).toEqual('yo'); // ... with the string 'yo'
});
it('We can check if the consumer called a method on the class instance', () => {
const mockedClassConsumer = new MockedClassConsumer();
expect(mockedMethodImpl).toHaveBeenCalledWith('bro');
// Checking for method call using the stored reference to the mock function
// It would be nice if there were a way to do this directly from MockedClass.mock
});
For me this kind of Replacing Real Class with mocked one worked.
// Content of real.test.ts
jest.mock("../RealClass", () => {
const mockedModule = jest.requireActual(
"../test/__mocks__/RealClass"
);
return {
...mockedModule,
};
});
var codeTest = require("../real");
it("test-real", async () => {
let result = await codeTest.handler();
expect(result).toMatch(/mocked.thing/);
});
// Content of real.ts
import {RealClass} from "../RealClass";
export const handler = {
let rc = new RealClass({doing:'something'});
return rc.realMethod("myWord");
}
// Content of ../RealClass.ts
export class RealClass {
constructor(something: string) {}
async realMethod(input:string) {
return "The.real.deal "+input;
}
// Content of ../test/__mocks__/RealClass.ts
export class RealClass {
constructor(something: string) {}
async realMethod(input:string) {
return "mocked.thing "+input;
}
Sorry if I misspelled something, but I'm writing it on the fly.