/ / Jest - próbna funkcja grubej strzałki w składniku React - javascript, Reagjs, Jestjs, Babel-Jest

Jest - mock fat arrow w komponencie React - javascript, reactjs, jestjs, babel-jest

Biorąc pod uwagę mój komponent i test poniżej, dlaczego mój confirmClickHandler metoda nadal jest wywoływana po uruchomieniu testu?

Uwaga: zauważyłem, że kiedy zmienię metodę z grubej strzałki na zwykłą funkcję, zostanie ona poprawnie wyszydzona. Czego tu brakuje?

class CalendarConfirmation extends React.Component {
...

confirmClickHandler = (e) =>  {
...
}
}

i mój test:

import React from "react";
import {mount} from "enzyme";
import CalendarConfirmation from "../components/CalendarConfirmation";

describe("Test CalendarConfirmation", () => {
let calendarConfirmation;
calendarConfirmation = mount (<CalendarConfirmation />);
calendarConfirmation.instance().confirmClickHandler = jest.fn();
...
}

Odpowiedzi:

1 dla odpowiedzi № 1

To działa dla mnie:

import React from "react"
import { mount, shallow } from "enzyme"

class Foo extends React.Component {
// babel transpiles this too Foo.prototype.canMock
protoMethod () {
// will be mocked
}

// this becomes an instance property
instanceMethod = () => {
return "NOT be mocked"
}

render () {
return (<div>{`${this.protoMethod()} ${this.instanceMethod()}`}</div>)
}
}

Foo.prototype.protoMethod = jest.fn().mockReturnValue("you shall")

it("should be mocked", () => {
const mock = jest.fn().mockReturnValue("be mocked")
const wrapper = mount(<Foo />)
wrapper.instance().instanceMethod = mock
wrapper.update()
expect(mock).toHaveBeenCalled()
})

Należy jednak pamiętać, że nie powiedzie się to podczas używania shallow zamiast zamontować.