为什么我的开玩笑功能会影响另一个测试

问题描述 投票:0回答:1

我有测试用例:

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': '[email protected]',
    'token': '123'
  }

  apiGateway.post = jest.fn().mockResolvedValue(authenticatedStub)

  loginPagePresenter.email = '[email protected]'
  loginPagePresenter.password = 'aaabbbcom'
  await loginPagePresenter.submit()
  expect(authRepository.user.token).toBe('123')
  expect(authRepository.user.email).toBe('[email protected]')
  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 = '[email protected]'
  loginPagePresenter.password = 'aaabbbcom'
  await loginPagePresenter.submit()
  expect(authRepository.user.token).toBe(null)
  expect(authRepository.user.email).toBe(null)
  expect(authRepository.authenticated).toEqual(false)
})

第一个测试是影响第二次测试。换句话说,如果我注释掉第一个测试,那么第二个测试就可以了。我检查了生产代码,它运行正常。但是第一个的模拟函数对第二个有副作用(看起来我无法重置返回的已解析函数)。

有人可以解释如何解决这个问题吗?

typescript jestjs
1个回答
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()清除每个人的模拟

在这里阅读更多相关信息:jest.clearAllMocks()mockFn.mockClear()

© www.soinside.com 2019 - 2024. All rights reserved.