You should be able to access the directive via the injector on the element you've returned.
The component:
@Component({
selector: 'app-my-custom-component',
template: `
<button id="with-directive" appMyCustomDirective>Click Me</button>
<button id="without-directive">Click Me Too</button>
`
})
export class MyCustomComponent {
}
The directive:
@Directive({
selector: '[appMyCustomDirective]'
})
export class MyCustomDirective {
public myVariable = 'hello there!';
}
The test:
describe('MyCustomComponent', () => {
let component: MyCustomComponent;
let fixture: ComponentFixture<MyCustomComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyCustomComponent,
MyCustomDirective
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyCustomComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('displays a button with the directive', () => {
const buttonWithDirective = fixture.debugElement.query(By.css('#with-directive'));
const directiveInstance: MyCustomDirective = buttonWithDirective.injector.get(MyCustomDirective);
expect(directiveInstance.myVariable).toBe('hello there!');
const buttonWithoutDirective = fixture.debugElement.query(By.css('#without-directive'));
//danger!! this will throw an exception because there is no directive
//const directiveInstance: MyCustomDirective = buttonWithDirective.injector.get(MyCustomDirective);
});
});