簡體   English   中英

React Jest/酶測試:useHistory Hook Breaks Test

[英]React Jest/Enzyme Testing: useHistory Hook Breaks Test

我對 React 還很陌生,所以請原諒我的無知。 我有一個組件:

const Login: FunctionComponent = () => {

    const history = useHistory();

    //extra logic that probably not necessary at the moment

    return (
        <div>
            <form action="">
                ...form stuff
            </form>
        </div>
    )
}

在嘗試編寫笑話/酶測試時,我編寫的一個測試用例失敗並顯示以下錯誤 ` › 遇到聲明異常

TypeError: Cannot read property 'history' of undefined`

我嘗試使用 jest 來模擬 useHistory,如下所示:

jest.mock('react-router-dom', () => ({
    useHistory: () => ({ push: jest.fn() })
}));

但這沒有任何作用:(我得到了同樣的錯誤。任何幫助將不勝感激

更新:

所以我想通了。 我在正確的道路上為useHistory()鈎子創建了一個模擬,我在錯誤的地方定義了。 需要在測試方法的范圍之外定義模擬(至少對於 useHistory),例如:

import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';

jest.mock('react-router', () => ({
    ...jest.requireActual('react-router'),
    useHistory: () => ({ push: jest.fn() })
}));

/**
 * Test suite describing Login test
describe('<LoginPage>', () => {
    test('should test something', () => {
         //expect things to happen
    });
})

上面的測試運行沒有失敗的歷史未定義。

所以我想通了。 通過為 useHistory() 鈎子創建模擬,我走在正確的道路上,我只是在錯誤的地方定義了它。 事實證明,模擬需要在測試方法的范圍之外定義(至少對於 useHistory),例如:

import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';

jest.mock('react-router', () => ({
    ...jest.requireActual('react-router'),
    useHistory: () => ({ push: jest.fn() })
}));

/**
 * Test suite describing Login test
 */
describe('<LoginPage>', () => {
    test('should test something', () => {
         //expect things to happen
    });
})

有了上述內容,測試運行時不會因未定義歷史記錄而失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM