我有测试用例:
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 href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="600120024e030f0d" rel="noreferrer noopener nofollow">[email protected]</a>',
'token': '123'
}
apiGateway.post = jest.fn().mockResolvedValue(authenticatedStub)
loginPagePresenter.email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e2c3e1ade0ecee" rel="noreferrer noopener nofollow">[email protected]</a>'
loginPagePresenter.password = 'aaabbbcom'
await loginPagePresenter.submit()
expect(authRepository.user.token).toBe('123')
expect(authRepository.user.email).toBe('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="553415377b363a38" rel="noreferrer noopener nofollow">[email protected]</a>')
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 href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0869486a266b6765" rel="noreferrer noopener nofollow">[email protected]</a>'
loginPagePresenter.password = 'aaabbbcom'
await loginPagePresenter.submit()
expect(authRepository.user.token).toBe(null)
expect(authRepository.user.email).toBe(null)
expect(authRepository.authenticated).toEqual(false)
})
第一个测试正在影响第二个测试。换句话说,如果我注释掉第一个测试,那么第二个测试就可以工作。我已经检查了生产代码它工作正常。但是第一个的模拟函数对第二个有副作用(看起来我无法重置返回的解析函数)。
有人可以解释一下如何解决这个问题吗?
最佳答案
您可以尝试在 beforeEach()
内的测试文件中添加 jest.clearAllMocks()
,如下所示:
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()
清除每个单独的模拟
在这里阅读更多相关信息:jest.clearAllMocks()和 mockFn.mockClear()
关于typescript - 为什么我的 Jest 函数模拟会影响另一个测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54805907/