Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我如何开玩笑地测试这个函数?_Reactjs_Unit Testing_Jestjs - Fatal编程技术网

Reactjs 我如何开玩笑地测试这个函数?

Reactjs 我如何开玩笑地测试这个函数?,reactjs,unit-testing,jestjs,Reactjs,Unit Testing,Jestjs,我目前对此文件的分支覆盖率为0%,我不确定如何测试 从“../router”导入{RouterState}; 从“../auth”导入{AuthStore}; export const DEFAULT_ROUTE='/account'; 导出常量HOME_ROUTE='/'; export const NOT_FOUND_ROUTE='NOT FOUND'; export const checkForUserSignedIn=()=>{ const authDataStore=new AuthS

我目前对此文件的分支覆盖率为0%,我不确定如何测试

从“../router”导入{RouterState};
从“../auth”导入{AuthStore};
export const DEFAULT_ROUTE='/account';
导出常量HOME_ROUTE='/';
export const NOT_FOUND_ROUTE='NOT FOUND';
export const checkForUserSignedIn=()=>{
const authDataStore=new AuthStore();
if(authDataStore.isAuthenticated){
返回承诺。解决();
}否则{
返回承诺。拒绝(新路线状态(回家路线));
}
};

为此,您可能需要提供
AuthStore
的“模拟实现”

模拟是测试中的一个概念,基本上意味着您“为某些东西提供一个替代实现”,在单元测试执行期间,应用程序代码将使用该实现

jest框架提供了模拟功能——在您的例子中是相关的

我在下面提供了一个粗略的示例,在您的代码和jest的上下文中说明这个概念。您需要为
AuthStore
提供一个或多个模拟,供测试使用,以允许您在不同的情况下(即
isAuthenticated
为true、false等)验证应用程序逻辑(即,
checkForUserSignedIn()
)是否按预期运行:

import * as User from 'YourUserModule' // ie, where checkForUserSignedIn is defined

// Tell jest you want to mock this module (assuming test located in same path as implementation)
// This module is where AuthStore is defined, which is the particular thing we're interested in mocking
jest.mock('../auth'); 

// Define a mock implementation of '../auth' for use in test
require('../auth')
.mockImplementation(() => {

    // An example of a mocked auth store class. This mocknever returns true for
    // isAuthenticated. We can use this mock to verify the behaviour of the
    // 'reject' code path
    class MockAuthStore {
        get isAuthenticated() {
            return false;
        }
    }

    // Return the mock class, to "replace" the existing implementation with this mock when running the test
    return {
        AuthStore : MockAuthStore
    }
})

// Now define your test
it('should reject when user is not authenticated', async () => {

    // An example of how you can verify that checkForUserSignedIn rejects when 
    // new AuthStore().isAuthenticated returns false
    await expect(User.checkForUserSignedIn()).rejects.toBeDefined();
});