reactjs - 我怎样才能开玩笑地测试这个功能?
问题描述
我目前对该文件的分支覆盖率为 0%,我不确定如何测试它。
import { RouterState } from '../router';
import { AuthStore } from '../auth';
export const DEFAULT_ROUTE = '/account';
export const HOME_ROUTE = '/';
export const NOT_FOUND_ROUTE = 'not-found';
export const checkForUserSignedIn = () => {
const authDataStore = new AuthStore();
if (authDataStore.isAuthenticated) {
return Promise.resolve();
} else {
return Promise.reject(new RouterState(HOME_ROUTE));
}
};
解决方案
为此,您可能需要提供AuthStore
.
模拟是测试中的一个概念,基本上意味着您“为某些东西提供替代实现”,您的应用程序代码在执行单元测试期间使用它。
jest 框架提供了模拟功能 - 在您的情况下,模块模拟是相关的。
我在下面提供了一个粗略的示例来说明您的代码上下文中的概念,并且开玩笑。您需要为 , 提供一个模拟(或多个模拟)以供AuthStore
您的测试使用,以允许您验证您的应用程序逻辑(即checkForUserSignedIn()
)在不同情况下(即何时isAuthenticated
为真、何时为假等)的行为是否符合预期):
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();
});
推荐阅读
- google-cloud-platform - Google Cloud Build 步骤日志在控制台中不可见
- python - 如何为 Android 构建 Instagram 机器人
- typescript - 在 TS 导出中包含 TypeScript 类型
- c - 在 Do while 循环中递增数字的问题
- swift - 如何在我的屏幕上随机生成敌人
- video.js - 记住视频在 VideoJS 中暂停的位置的功能
- api - 邮递员有没有办法从 GET 请求中读取响应数据,然后使用 IF THEN 语句来运行 POST 请求?
- python - 如何从 VSCode 中的其他脚本导入?
- java - 方法重构需要去掉多个if条件
- html - 更改div中的弹性顺序?