I have a group of classes that receive some dependencies outside angular in this way.
import {TypeATest} from '...../TypeA.model'
import { TypeBTest } from '..../TypeB.model'
import { SomeDependency } from './services/SomeDependency'
import { SomeAnother } from './services/SomeAnother'
// ....
@Injectable({
providedIn: 'root'
})
export class TestingService {
this.activeTest: AnyTestType;
constructor(private readonly injectorService: InjectorService) {}
loadTest(TypeOfTest) {
const someDependency = this.injectorService.get(SomeDependency)
const someAnother = this.injectorService.get(SomeAnother)
switch(TypeOfTest) {
case TypeA:
injector
this.activeTest = new TypeATest(someDependency, someAnother);
break;
case TypeB:
this.activeTest = new TypeBTest(someAnother);
break;
}
}
startTest(){
this.activeTest.start()
}
// .. more this.activeTest uses...
}
I am unit testing the service that loads that external classes but I do not want to create TypeATest
, TypeBTest
or similar but just mock the result (they all have the same API) but I am not able to find how to mock them. Is there a way to do this?
The two constructors are named exports of their respective modules.
You can mock the entire module using jest.mock
with a module factory:
jest.mock('...../TypeA.model', () => {
const start = jest.fn();
const result = { start };
return jest.fn(() => result);
});
test('something', () => {
// ...
});
...or mock only the named export of the module using jest.spyOn
:
import * as TypeB from '..../TypeB.model';
test('something', () => {
const spy = jest.spyOn(TypeB, 'TypeBTest');
const start = jest.fn();
spy.mockReturnValue({ start });
// ...
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.