【问题标题】:jest describe suite fails but running test independently succeeds开玩笑描述套件失败,但独立运行测试成功
【发布时间】:2020-05-21 09:18:52
【问题描述】:

当我单独运行每个测试时,它们都成功了。但是当我通过npm test 一起运行它们时,第二个测试失败了:

Expected number of calls: 2
Received number of calls: 4

我有以下代码:(短而删节)

describe('checkDonations', () => {
test('it should call twice (test 1)', async () => {
    const axiosSpy = jest.spyOn(axios.default, 'get')
        .mockImplementation(() => {
            return new Promise(resolve => {
                resolve({
                    data: {
                        status: [
                            {
                                "created": "2020-04-08 21:20:17",
                                "timestamp": "1586373617",
                                "statusName": "new"
                            }
                        ]
                    }
                })
            })
        });

    await checkDonations(null, {});

    expect(axiosSpy).toHaveBeenCalledTimes(2);
})

test('it should call twice (test 2)', async () => {
    const axiosSpy = jest.spyOn(axios.default, 'get')
        .mockImplementation(() => {
            return new Promise(resolve => {
                resolve({
                    data: {
                        status: [
                            {
                                "created": "2020-04-08 21:20:17",
                                "timestamp": "1586373617",
                                "statusName": "final_success"
                            }
                        ]
                    }
                })
            })
        });

    await checkDonations(null, {});

    expect(axiosSpy).toHaveBeenCalledTimes(2);
})
})

测试被剪切以显示问题。如您所见,它们几乎相等,并且每个人都有自己的间谍常量。只是 axiosSpy 的返回值不同。所以我不能把它放在before each

为什么我通过npm test 运行第二个测试失败了?

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    您也许应该在 beforeEach 中重置您的模拟?我使用类似下面的代码:

    beforeEach(() => jest.resetAllMocks())
    

    【讨论】:

    • 谢谢,这行得通!我仍然很困惑。这是测试框架的通常/正常行为吗?
    • @EroStefano 是的。考虑在 Jest 配置中启用 resetMocks,由于某种原因它不是默认设置。
    • 它对我不起作用!
    • @amir 我也不知道!
    • 我遇到了同样的问题,这解决了我的问题,谢谢!但是,我已经指定了 beforeEach(() => jest.clearAllMocks()) ....应该工作相同,对吧?还是个谜
    【解决方案2】:

    删除构建生成的文件夹(例如:dist)并重试。它对我有用。

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 2020-11-21
      • 2018-02-13
      • 2018-12-17
      • 2017-11-19
      • 1970-01-01
      • 2018-05-01
      • 2018-09-25
      相关资源
      最近更新 更多