开玩笑描述套件失败但独立运行测试成功

Ero*_*ano 9 typescript jestjs

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

Expected number of calls: 2
Received number of calls: 4
Run Code Online (Sandbox Code Playgroud)

我有以下代码:(简短且精简)

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);
})
})
Run Code Online (Sandbox Code Playgroud)

测试被剪切以显示问题。正如你所看到的,他们几乎是平等的,并且每个人都有自己的间谍倾向。只是axiosSpy的返回值不同。所以我不能把它放在before each.

为什么当我运行第二个测试时会失败npm test

Gil*_*e59 13

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

beforeEach(() => jest.resetAllMocks())
Run Code Online (Sandbox Code Playgroud)

  • @EroStefano 是的。考虑在 Jest 配置中启用 resetMocks,由于某种原因它不是默认设置。 (2认同)