I am using a directive to get the data from input used as a filter text.
here is my hostlistener in the directive:
#HostListener('input', ['$event.target.value'])
public onChangeFilter(event: any): void {
console.log('input event fired, value: ' + event);
this.columnFiltering.filterString = event;
this.filterChanged.emit({filtering: this.columnFiltering});
}
this code is working perfectly, I am unable to unit test the same.
I have subscribed to the filterChanged EventEmitter, in my unit test to check the value.
I tried simulating keypress event to change value and also tried settings value attribute. None of these is working for me.
here is my spec file:
describe('Table View', () => {
let fixture: ComponentFixture<any>;
let context: TableComponent;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
TableComponent,
],
imports: [TableModule],
});
fixture = TestBed.createComponent(TableComponent);
context = fixture.componentInstance;
});
it('should allow filter', () => {
const element = fixture.nativeElement;
context.config = config;
fixture.detectChanges();
let tableChangeCount = 0;
let tableEvent: any;
context.tableChanged.subscribe((event: any) => {
tableChangeCount++;
tableEvent = event;
});
// Check if table exists
let inputElement = element.querySelectorAll('tr')[1].querySelector('input');
let e = new KeyboardEvent("keypress", {
key: "a",
bubbles: true,
cancelable: true,
});
inputElement.dispatchEvent(e);
});
});
I tried setting value:
let attrs = inputElement.attributes;
inputElement.setAttribute('value', 'abc');
for (let i = attrs.length - 1; i >= 0; i--) {
// Attribute value is set correctly
if (attrs[i].name === 'value') {
console.log(attrs[i].name + "->" + attrs[i].value);
}
}
Can anyone please help me, how can I unit test the same?
I've had some trouble simulating a keypress in a unit test also. But came across an answer by Seyed Jalal Hosseini. It might be what you're after.
If you're attempting to simulate a keypress you can trigger an event by calling dispatchEvent(new Event('keypress')); on the element.
Here is the answer I'm referring to which gives more detail : https://stackoverflow.com/a/37956877/4081730
If you want to set the key that was pressed, this can be done also.
const event = new KeyboardEvent("keypress",{
"key": "Enter"
});
el.dispatchEvent(event);
Further information I've just come across: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
If you wish to use a key code (or "which"), you can do this:
// #HostListener('document:keypress')
const escapeEvent: any = document.createEvent('CustomEvent');
escapeEvent.which = 27;
escapeEvent.initEvent('keypress', true, true);
document.dispatchEvent(escapeEvent);
it('should trigger a TAB keypress event on an element', () => {
const tabKeypress = new KeyboardEvent('keypress', {
// #ts-ignore
keyCode: 9, // Tab Key
cancelable: true
});
const myTableEle = debugEle.nativeElement.querySelector('.your-element');
myTableEle.dispatchEvent(tabKeypress);
fixture.detectChanges();
});
// #ts-ignore :- is to remove TS warning because keyCode is deprecated. Its not needed in case you want to set "key" property of KeyboardEvent.
Related
I am trying to test AsyncTypeahead from react-bootstrap-typeahead.
I have a very simple test component :
class AsyncTypeahead2 extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
isLoading: false,
};
}
render() {
return ( <AsyncTypeahead
isLoading={this.state.isLoading}
onSearch={query => {
this.setState({isLoading: true});
fetch("http://www.myHTTPenpoint.com")
.then(resp => resp.json())
.then(json => this.setState({
isLoading: false,
options: json.items,
}));
}}
options={this.state.options}
labelKey={option => `${option.stateName}`}
/> )
}
}
const url = "http://www.myHTTPenpoint.com"
fetchMock
.reset()
.get(
url,
{
items: [
{id:1, stateName:"Alaska"},
{id:2, stateName:"Alabama"}
]
},
);
(Note that the URL is mocked to return two elements)
When I run this in my storybook it looks fine :
But if I want to test it (with Enzyme) it does not recognise the < li > items that pop up.
let Compoment =
<div>Basic AsyncTypeahead Example
<AsyncTypeahead2/>
</div>
const wrapper = mount(Compoment);
let json = wrapper.html();
let sel = wrapper.find(".rbt-input-main").at(0)
sel.simulate('click');
sel.simulate('change', { target: { value: "al" } });
expect(wrapper.find(".rbt-input-main").at(0).getElement().props.value).toBe("al")
expect(wrapper.find(".dropdown-item").length).toBe(2) //but get just 1 element "Type to Search..."
Instead of finding two "dropdown-item" items there is just one item with the text "Type to Search...".
Is the AynchTypeahead not updating the DOM correctly with respect to Enzyme?
<AsyncTypeahead> is asynchronous. On the other hand simulate() is synchronous. So at the time you get to expect() AsyncTypeahead not even started to populate the dropdown with <li> elements. You need to wait for it.
It's not specified, but it looks like you are using fetch-mock package.
There is the flush function which
Returns a Promise that resolves once all fetches handled by fetch-mock have resolved
So this:
...
sel.simulate('click');
sel.simulate('change', { target: { value: "al" } });
await fetchMock.flush() // !!!
expect(wrapper.find(".rbt-input-main").at(0).getElement().props.value).toBe("al")
expect(wrapper.find(".dropdown-item").length).toBe(2)
should work.
...But probably it won't. Because
fetchMock.mock(...)
fetch(...)
await fetchMock.flush()
does work, but
fetchMock.mock(...)
setTimeout(() => fetch(...), 0)
await fetchMock.flush()
does not. await fetchMock.flush() returns right away if there was no call of fetch. And probably there won't be. Because <AsyncTypeahead> debounces.
(By the way, you can also try to mock fetch on a per-test basis. Just in case.)
So I see two options:
Use something else instead of fetch-mock package. Where you can resolve your own Promises on mocked requests completion.
https://tech.travelaudience.com/how-to-test-asynchronous-data-fetching-on-a-react-component-ff2ee7433d71
import waitUntil from 'async-wait-until';
...
test("test name", async () => {
let Compoment = <AsyncTypeahead2/>
...
await waitUntil(() => wrapper.state().isLoading === false);
// or even
// await waitUntil(() => wrapper.find(".dropdown-item").length === 2, timeout);
expect(...)
})
This options if not pretty. But maybe it's your only option - there is not only the fetch-mock you should worry about. setState also asynchronous... and it looks like there is no pretty way to check when it's done updating the state and the DOM without changing the real code (which is quite undesirable).
The exact solution to my problem is in the following code (copy and paste into a JS file to see it work).
Things to note :
I needed to use the waitUntil function from the async-wait-until library. fetch-mock on its own does not provide the functionality to test async code.
I needed to add an ugly hack at global.document.createRange because of some tooltip issue with react-bootstrap-typeahead and jest.
use waitUntil to wait on changes on the internal state of the component
It is very important to call wrapper.update() to update the DOM afterwards.
..
import React, {Component} from 'react';
import waitUntil from 'async-wait-until';
import {mount} from "enzyme";
import fetchMock from "fetch-mock";
import {AsyncTypeahead} from "react-bootstrap-typeahead";
describe('Autocomplete Tests ', () => {
test(' Asynch AutocompleteInput ', async () => {
class AsyncTypeaheadExample extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
isLoading: false,
finished: false
};
}
render() {
return (<AsyncTypeahead
isLoading={this.state.isLoading}
onSearch={query => {
this.setState({isLoading: true});
fetch("http://www.myHTTPenpoint.com")
.then(resp => resp.json())
.then(json => this.setState({
isLoading: false,
options: json.items,
finished: true
}));
}}
options={this.state.options}
labelKey={option => `${option.stateName}`}
/>)
}
}
const url = "http://www.myHTTPenpoint.com"
fetchMock
.reset()
.get(
url,
{
items: [
{id: 1, stateName: "Alaska"},
{id: 2, stateName: "Alabama"}
]
},
);
let Compoment =
<AsyncTypeaheadExample/>
// ugly hacky patch to fix some tooltip bug
// https://github.com/mui-org/material-ui/issues/15726
global.document.createRange = () => ({
setStart: () => {
},
setEnd: () => {
},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
let wrapper = mount(Compoment);
let sel = wrapper.find(".rbt-input-main").at(0)
sel.simulate('click');
sel.simulate('change', {target: {value: "al"}});
expect(wrapper.find(".rbt-input-main").at(0).getElement().props.value).toBe("al")
//now the async stuff is happening ...
await waitUntil(() => {
return wrapper.state().finished === true;
}, 3000); //wait about 3 seconds
wrapper.update() //need to update the DOM!
expect(wrapper.find(".dropdown-item").length).toBe(2) //but get just 1 element "Type to Search..."
})
});
UPDATE
I can also compare on wrapper items rather than doing a direct comparison on the state :
//now the async stuff is happening ...
await waitUntil(() => {
wrapper.update() //need to update the DOM!
return wrapper.find(".dropdown-item").length > 1
}, 3000); //wait about 3 seconds
This is probably better because it means i dont need to know about the component internals.
I have a watcher on language in my component
I get the current language from a getter ( its value is changed from the Toolbar language selector, default in state.language is "en")
ContactForm.vue
...
data() {
return {
contactLang: "",
...
};
},
computed: {
...mapGetters(["language"]),
},
watch: {
language(newLanguage) {
console.lo("language changed to: ", newLanguage);
this.contactLang = newLanguage;
this.$validator.localize(newLanguage);
}
},
======================
I am trying to test the watch block
ContactForm.spec.js
beforeEach(() => {
// create a fresh store instance for every test case.
storeMocks = createStoreMocks();
options = {
sync: false,
provide: () => ({
$validator: v
}),
store: storeMocks.store,
i18n
};
wrapper = shallowMount(ContactForm, options);
});
it("change the form language when locale changed", () => {
// update the Vuex store language , but it does not trigger the watcher ...
wrapper.vm.$store.state.language = "fr";
expect(wrapper.vm.contactLang).toBe("fr");
});
Is there any way to test this watch block , or should I restructure my code to avoid such testing in this component...
I solved the issue... watchers are asynchronous so I just delay the assertion
it("change the form language when locale changed", () => {
// pdate the Vuex store language , but it does not trigger the watcher ...
wrapper.vm.$store.state.language = "fr";
setTimeout(() => {
// assert changes operated by watcher
expect(wrapper.vm.contactLang).toBe("fr");
}, 50);
});
1: The mat-select has 4 values, 1,2,3,4.
The code below works good for the select. So I'd like to share if it helps the readers.
it('check the length of drop down', async () => {
const trigger = fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement;
trigger.click();
fixture.detectChanges();
await fixture.whenStable().then(() => {
const inquiryOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
expect(inquiryOptions.length).toEqual(4);
});
});
2: I need another test to verify the default value in the same
mat-select is 3 or not. When page loads the default value for the drop down is set to 3.
it('should validate the drop down value if it is set by default', async () => {
const trigger = fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement;
trigger.click();
fixture.detectChanges();
await fixture.whenStable().then(() => {
const inquiryOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
const value = trigger.options[0].value;
expect(value).toContain(3);
});
});
Any help is appreciated.
This one is worked for me in Angular 7
const debugElement = fixture.debugElement;
// open options dialog
const matSelect = debugElement.query(By.css('.mat-select-trigger')).nativeElement;
matSelect.click();
fixture.detectChanges();
// select the first option (use queryAll if you want to chose an option)
const matOption = debugElement.query(By.css('.mat-option')).nativeElement;
matOption.click();
fixture.detectChanges();
fixture.whenStable().then( () => {
const inputElement: HTMLElement = debugElement.query(By.css('.ask-input')).nativeElement;
expect(inputElement.innerHTML.length).toBeGreaterThan(0);
});
After some testing I found an answer (at least for my code) and hope, that this is helpful to you as well:
When I looked at the DOM, when the application is running, I noticed that the default value of the mat-select is inside this DOM structure:
<mat-select>
<div class="mat-select-trigger">
<div class="mat-select-value">
<span class="something">
<span class="something">
The value is here!
But in my case, I had a form builder in my .ts file and it was used in ngOnInit(). It seems that the normal TestBed.createComponent(MyComponent) does not call ngOnInit(). So I had to do that in order to get the value. Otherwise there was just a placeholder span.
So, my final code looks like this:
it('should validate the drop down value if it is set by default', async () => {
const matSelectValueObject: HTMLElement = fixture.debugElement.query(By.css('.mat-select-value')).nativeElement;
component.ngOnInit();
fixture.detectChanges();
const innerSpan =
matSelectValueObject.children[0].children[0]; // for getting the inner span
expect(innerSpan.innerHTML).toEqual(3); // or '3', I did not test that
});
By the way I'm using Angular 7, in case this matters.
Helper method for your page object to set the option by text:
public setMatSelectValue(element: HTMLElement, value: string): Promise<void> {
// click on <mat-select>
element.click();
this.fixture.detectChanges();
// options will be rendered inside OverlayContainer
const overlay = TestBed.get(OverlayContainer).getContainerElement();
// find an option by text value and click it
const matOption = Array.from(overlay.querySelectorAll<HTMLElement>('.mat-option span.mat-option-text'))
.find(opt => opt.textContent.includes(value));
matOption.click();
this.fixture.detectChanges();
return this.fixture.whenStable();
}
let loader = TestbedHarnessEnvironment.loader(fixture);
const matSelect = await loader.getAllHarnesses(MatSelectHarness);
await matSelect[0].clickOptions();
const options = await matSelect[0].getOptions();
expect(await options[0].getText()).toMatch("");
expect(await options[1].getText()).toMatch('option1');
expect(await options[2].getText()).toMatch('option2');
const select = await loader.getAllHarnesses(MatSelectHarness);
//test to check there are how many mat selects
expect(select.length).toBe(1);
//open the mat select
await select[0].open();
//Get the options
const options = await select[0].getOptions();
//test to check option length
expect(options.length).toBe(1);
//test to check mat options
expect(await options[0].getText()).toBe('option 1');
expect(await options[1].getText()).toBe('option 2');
I would like to change the value of an input field from within an Angular 2 unit test.
<input type="text" class="form-control" [(ngModel)]="abc.value" />
I can't just change the ngModel because abc object is private:
private abc: Abc = new Abc();
In Angular 2 testing, can I simulate the user typing into the input field so that the ngModel will be updated with what the user has typed from within a unit test?
I can grab the DebugElement and the nativeElement of the input field without a problem. (Just setting a the value property on the nativeElement of the input field doesn't seem to work as it doesn't update the ngModel with what I've set for the value).
Maybe inputDebugEl.triggerEventHandler can be called, but I'm not sure what arguments to give it so it will simulate the user having typed a particular string of input.
You're right that you can't just set the input, you also need to dispatch the 'input' event. Here is a function I wrote earlier this evening to input text:
function sendInput(text: string) {
inputElement.value = text;
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
return fixture.whenStable();
}
Here fixture is the ComponentFixture and inputElement is the relevant HTTPInputElement from the fixture's nativeElement. This returns a promise, so you'll probably have to resolve it sendInput('whatever').then(...).
In context: https://github.com/textbook/known-for-web/blob/52c8aec4c2699c2f146a33c07786e1e32891c8b6/src/app/actor/actor.component.spec.ts#L134
Update:
We had some issues getting this to work in Angular 2.1, it didn't like creating a new Event(...), so instead we did:
import { dispatchEvent } from '#angular/platform-browser/testing/browser-util';
...
function sendInput(text: string) {
inputElement.value = text;
dispatchEvent(fixture.nativeElement, 'input');
fixture.detectChanges();
return fixture.whenStable();
}
The accepted solution didn't quite work for me in Angular 2.4. The value I had set was not appearing in the (test) UI, even after detectChanges() was called.
The way I got it to work was to set up my test as follows:
describe('TemplateComponent', function () {
let comp: TemplateComponent;
let fixture: ComponentFixture<TemplateComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ FormsModule ],
declarations: [ TemplateComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TemplateComponent);
comp = fixture.componentInstance;
});
it('should allow us to set a bound input field', fakeAsync(() => {
setInputValue('#test2', 'Tommy');
expect(comp.personName).toEqual('Tommy');
}));
// must be called from within fakeAsync due to use of tick()
function setInputValue(selector: string, value: string) {
fixture.detectChanges();
tick();
let input = fixture.debugElement.query(By.css(selector)).nativeElement;
input.value = value;
input.dispatchEvent(new Event('input'));
tick();
}
});
My TemplateComponent component has a property named personName in this example, which was the model property I am binding to in my template:
<input id="test2" type="text" [(ngModel)]="personName" />
I also had trouble getting jonrsharpe's answer to work with Angular 2.4. I found that the calls to fixture.detectChanges() and fixture.whenStable() caused the form component to reset. It seems that some initialization function is still pending when the test starts. I solved this by adding extra calls to these methods before each test. Here is a snippet of my code:
beforeEach(() => {
TestBed.configureTestingModule({
// ...etc...
});
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
usernameBox = fixture.debugElement.query(By.css('input[name="username"]'));
passwordBox = fixture.debugElement.query(By.css('input[type="password"]'));
loginButton = fixture.debugElement.query(By.css('.btn-primary'));
formElement = fixture.debugElement.query(By.css('form'));
});
beforeEach(async(() => {
// The magic sauce!!
// Because this is in an async wrapper it will automatically wait
// for the call to whenStable() to complete
fixture.detectChanges();
fixture.whenStable();
}));
function sendInput(inputElement: any, text: string) {
inputElement.value = text;
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
return fixture.whenStable();
}
it('should log in correctly', async(() => {
sendInput(usernameBox.nativeElement, 'User1')
.then(() => {
return sendInput(passwordBox.nativeElement, 'Password1')
}).then(() => {
formElement.triggerEventHandler('submit', null);
fixture.detectChanges();
let spinner = fixture.debugElement.query(By.css('img'));
expect(Helper.isHidden(spinner)).toBeFalsy('Spinner should be visible');
// ...etc...
});
}));
I've got a HighlightDirective which does highlight if the mouse enters an area, like:
#Directive({
selector: '[myHighlight]',
host: {
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)': 'onMouseLeave()'
}
})
export class HighlightDirective {
private _defaultColor = 'Gainsboro';
private el: HTMLElement;
constructor(el: ElementRef) { this.el = el.nativeElement; }
#Input('myHighlight') highlightColor: string;
onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
onMouseLeave() { this.highlight(null); }
private highlight(color:string) {
this.el.style.backgroundColor = color;
}
}
Now I want to test, if the (right) methods are called on event. So something like this:
it('Check if item will be highlighted', inject( [TestComponentBuilder], (_tcb: TestComponentBuilder) => {
return _tcb
.createAsync(TestHighlight)
.then( (fixture) => {
fixture.detectChanges();
let element = fixture.nativeElement;
let component = fixture.componentInstance;
spyOn(component, 'onMouseEnter');
let div = element.querySelector('div');
div.mouseenter();
expect(component.onMouseEnter).toHaveBeenCalled();
});
}));
With the testclass:
#Component({
template: `<div myHighlight (mouseenter)='onMouseEnter()' (mouseleave)='onMouseLeave()'></div>`,
directives: [HighlightDirective]
})
class TestHighlight {
onMouseEnter() {
}
onMouseLeave() {
}
}
Now, I've got the message:
Failed: div.mouseenter is not a function
So, does anyone know, which is the right function (if it exists)? I've already tried using click()..
Thanks!
Instead of
div.mouseenter();
this should work:
let event = new Event('mouseenter');
div.dispatchEvent(event);
additional info to gunter's answer, you need to send additional parameter to the Event. Or it won't trigger.
Refer to: https://developer.mozilla.org/en-US/docs/Web/API/Event/composed
let event = new Event('mouseenter', {composed: true});
would be the correct way of defining the event for the HTMLElement to invoke the Event.
Additionally as well, I had missed the following from the create component:
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges(); // <<< THIS
If you do it will appear like the test is working, but by using coverage, you will find the event is not triggered.
A nasty issue to spot.