Mocking Constructors
kanben-a opened this issue · 4 comments
Hi!
I'm just a TypeScript beginner, so I may not not have a full grasp on the thing I'm trying to do:
I'm currently trying to mock a constructor of an imported class- is there any way? Currently your library only allows to mock away functions.
class Test{
constructor(hi:string){
//how can i make sure this is called with the correct string
}
}
EDIT:
TypeScript now compiles but throws the following error:
TypeError: Cannot stub non-existent own property default
at Sandbox.stub (node_modules/sinon/lib/sinon/sandbox.js:308:19)
at Function.ImportMock.mockFunction (node_modules/ts-mock-imports/src/import-mock.ts:18:18)
This is my test code:
var queue_stub = ImportMock.mockFunction(queue);
queue_stub.callsFake(function(queue_name, { redis }) {
expect(queue_name).to.be.a("string");
expect(redis).to.equal(mock_redis_config);
return mock_queue;
});
(I'm trying to mock Bull)
What does the import of your test look like?
That error is thrown when your code is importing the library as import { Queue } from 'queue'
which would mean you need to call ImportMock.mockFunction(queue, 'Queue')
as ImportMock needs to know which export to replace.
Thanks for your repsonse!
My import looks like this:
import * as Queue from bull
this is needed because the bull package exposes the namespace and its constructor under the same name:
declare const Bull: {
/* tslint:disable:no-unnecessary-generics unified-signatures */
<T = any>(queueName: string, opts?: Bull.QueueOptions): Bull.Queue<T>;
<T = any>(queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue<T>;
new <T = any>(queueName: string, opts?: Bull.QueueOptions): Bull.Queue<T>;
new <T = any>(queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue<T>;
/* tslint:enable:no-unnecessary-generics unified-signatures */
};
declare namespace Bull {
interface RateLimiter {
...
from: @types/bull
not sure if it helps:
import * as someModule from 'some-module';
class Mocked extends someModule.default {
constructor(args) {
super(args);
// Spectate args
}
}
const mockManager = ImportMock.mockOther(someModule, 'default', Mocked);
Hmm, this is definitely a good way to start out and helps me to monitor stuff.
Thanks for your help!