我有测试用例:
import { loginPagePresenter } from './LoginPagePresenter'
import { apiGateway } from 'config/gatewayConfig'
import { authRepository } from './AuthRepository'
it('should update the auth repository user with the token, email and set authenticated observable when successesful api call', async () => {
const authenticatedStub = {
'success': true,
'message': 'successful login',
'email': 'a@b.com',
'token': '123'
}
apiGateway.post = jest.fn().mockResolvedValue(authenticatedStub)
loginPagePresenter.email = 'a@b.com'
loginPagePresenter.password = 'aaabbbcom'
await loginPagePresenter.submit()
expect(authRepository.user.token).toBe('123')
expect(authRepository.user.email).toBe('a@b.com')
expect(authRepository.authenticated).toBe(true)
})
it('should not update the user model when NOT successesful api call', async () => {
const notAutenticatedStub = {
'success': false,
'message': 'bad login',
'email': '',
'token': ''
}
apiGateway.post = jest.fn().mockResolvedValue(notAutenticatedStub)
loginPagePresenter.email = 'a@b.com'
loginPagePresenter.password = 'aaabbbcom'
await loginPagePresenter.submit()
expect(authRepository.user.token).toBe(null)
expect(authRepository.user.email).toBe(null)
expect(authRepository.authenticated).toEqual(false)
})
第一个测试正在影响第二个测试。换句话说,如果我注释掉第一个测试,则第二个测试有效。我已经检查了生产代码是否有效。但是第一个的模拟功能对第二个具有副作用(看来我无法重置返回的已解析函数)。
有人可以解释如何解决此问题吗?
答案 0 :(得分:0)
您可以尝试在jest.clearAllMocks()
内的测试文件上添加beforeEach()
,例如:
import { loginPagePresenter } from './LoginPagePresenter'
import { apiGateway } from 'config/gatewayConfig'
import { authRepository } from './AuthRepository'
beforeEach(() => {
jest.clearAllMocks();
});
it('should update the auth repository user ...', async () => {
...
})
it('should not update the user model when NOT ...', async () => {
...
})
这将在每次测试运行之前清除所有模拟。
或者您也可以使用mockFn.mockClear()