我目前对该文件的分支覆盖率为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));
}
};
答案 0 :(得分:2)
为此,您可能需要提供AuthStore
的“模拟实现”。
模拟是测试中的一个概念,基本上意味着您“为某些事情提供了替代实现”,该代码在执行单元测试期间由应用程序代码使用。
玩笑框架提供了模拟功能-在您的情况下,module mocking是相关的。
我在下面提供了一个粗略的示例,以在您的代码上下文中说明这个概念。您需要为AuthStore
提供一个(或多个)模拟,供测试使用,以使您能够验证应用逻辑(即checkForUserSignedIn()
)在不同情况下的行为是否符合预期(即isAuthenticated
为true,false等时):
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();
});