Baru-baru ini saya ingin menguji bahwa beberapa metode kustom dipanggil secara kondisional di metode componentDidMount
dari sebuah komponen React.
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
Saya menggunakan Jest sebagai kerangka kerja pengujian saya, yang mencakup jest.fn()
untuk mocks/spies. Saya telah membaca bahwa hal ini akan cukup sepele untuk diuji dengan Sinon, dengan melakukan sesuatu seperti berikut ini:
sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
Saya mencoba membuat ulang ini dengan Jest seperti ini:
Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
Kode ini gagal dan melempar kesalahan berikut:
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
Apakah mungkin untuk menguji fungsi ini dengan Jest? Dan jika demikian, bagaimana caranya?
Kuncinya adalah menggunakan metode spyOn
jests. Seharusnya seperti ini:
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
Seperti yang ditemukan di sini, misalnya: https://stackoverflow.com/questions/40393486/test-if-function-is-called-react-and-enzyme
Harap diperhatikan ini juga merupakan praktik terbaik untuk menghapus fungsi mata-mata setelah setiap uji coba
let spy
afterEach(() => {
spy.mockClear()
})
https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks
Saya tahu ini agak terlambat, tetapi saya menemukan ini dan akan menyarankan bahwa untuk menguji componentDidMount
memulai panggilan ke metode bersarang Anda bahwa pengujian Anda harus terlihat seperti itu:
Modul
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
Tes - Baik
it('should call methodName during componentDidMount', () => {
const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName');
const wrapper = mount(<MyComponent {...props} />);
expect(methodNameFake).toHaveBeenCalledTimes(1);
});
Jika anda memanggil componentDidMount
maka pernyataan bahwa methodName
dipanggil melalui componentDidMount
lebih valid.
Test - Bad
it('should call methodName during componentDidMount', () => {
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
}
Dengan menulis test seperti ini - Anda memanggil metode dan kemudian menyatakan bahwa metode itu telah dipanggil. Yang tentu saja itu akan terjadi karena Anda baru saja memanggilnya.