我正在尝试为连接到Firebase的自定义React挂钩编写单元测试。由于我不想在运行测试时实际连接到Firebase,因此我模拟了Firebase和Firebase / app。它们是超级简单的模拟,只返回代码实际使用的功能。
const binaryImg = atob(base64String);
const length = binaryImg.length;
const arrayBuffer = new ArrayBuffer(length);
const uintArray = new Uint8Array(arrayBuffer);
for (let i = 0; i < length; i++) {
uintArray[i] = binaryImg.charCodeAt(i);
}
const fileBlob = new Blob([uintArray], { type: 'application/pdf' });
saveAs(fileBlob, 'filename.pdf');
// __mocks__/firebase.js
export default {
analytics: jest.fn(),
storage: jest.fn()
};
这对我的某些测试而言效果很好,但是在某些情况下,我需要更改模拟文件中的值。在特定情况下,我想确保Firebase出现问题时能够捕获错误,因此我想将// __mocks__/firebase/app.js
const auth = jest.fn().mockReturnValue({
currentUser: {
getIdTokenResult: jest.fn().mockReturnValue({
claims: jest.fn()
})
},
onIdTokenChanged: jest.fn()
});
export default {
initializeApp: jest.fn(),
auth
}
的值改为currentUser
(这会使我的钩子抛出错误,我可以测试一下。
但是,我无法弄清楚如何为一个特定测试更改模拟文件,而为其他测试保留相同的文件。
这是我的测试文件的示例
false
我似乎没有做任何事情致使import { renderHook, cleanup } from '@testing-library/react-hooks';
import useFirebase from 'src/App/useFirebase';
/*
* For some reason, jest.mock('firebase') doesnt use my custom mock files,
* so I have to explicitly tell jest which files to use
*/
jest.mock('firebase', () => jest.requireActual('../../../__mocks__/firebase'));
jest.mock('firebase/app', () => jest.requireActual('../../../__mocks__/firebase/app'));
afterEach(cleanup);
test('returns rejected promise if theres an error', async () => {
// Trying to override the mocked module, with a slightly different one.
// However, useFirebase.js still uses the first mocked module
jest.mock('firebase/app', () => ({
auth: jest.fn().mockReturnValue({
currentUser: false
}),
initializeApp: jest.fn()
}));
expect.assertions(1);
const { result } = renderHook(() => useFirebase());
// verifyGroup is a function in useFirebase(), that I'm trying to make return
// a rejected promise
await result.current.verifyGroup()
.catch(e => {
expect(e).not.toBeNull();
});
});
使用我的第二个模拟而不是我的第一个模拟。
我该如何实现?
编辑:我相信部分问题是我使用的是ES6导入,无法与模拟功能很好地配合。