lundi 19 août 2019

React, TypeScript &RxJS testing with Jest not working

I have a simple button component in React TypeScript, I using fromEvent method to translate click event to Observable wrapper of RxJs it is defiened fromEvent(el:HTMLElement, eventType:string) in RxJS

type NullableObservarbel = Observable<any> | null
type NUllabe = HTMLElement | null

    export const makeObservable = (el:NUllabe, eventType:string):NullableObservarbel => el ? fromEvent(el, eventType) : null;
type Props = {
    interval?: number // timee interval in millisecond
    label?:string
}

const Button:SFC<Props> = ({label}:Props) => {
    const btn = useRef(null)
    useEffect(() => {
        if(btn.current !== null){
            const observable = makeObservable(btn.current, 'click')
        }
    }, [])
    return <button ref={btn}>{label}</button>
}

As you can see makeObservable method,

  1. I want to test this method with Jest --> if I pass proper HTMLElement and string as an argument it should return Observable
  2. I want to simulate click event then I want to check `returned observable is working and subscribers of that observable are triggering.

But none of this test are not working as expected.

This is the first test I haven't implement the second one because the first one already not working as expected.

import React from 'react'
import { shallow, mount } from 'enzyme'
import Button, {makeObservable} from './Button'
import {Observable} from 'rxjs'

describe('Observable', () => {
    it('should create observable', () => {
        const wrapper = shallow(<Button />)
        const el = wrapper.find('button')
        const observable = makeObservable(el, 'click') // here i have the issue
        expect(observable instanceof Observable).toBe(true)
    })
})

The biggest problem is I can't get HTMLElement type from wrapper so i just use find button and pass the result as an element, But

expect(observable instanceof Observable).toBe(true) this line is always passing event if I pass null as argument for el to makeObservable.

Please help me to test properly these scenarios.

Aucun commentaire:

Enregistrer un commentaire