【发布时间】:2022-02-10 08:57:49
【问题描述】:
我正在尝试使用 react-testing-library 测试单击按钮后 window.location.href 何时更改。我在网上看到过一些示例,您可以手动更新测试用例中的 window.location.href,例如 window.location.href = 'www.randomurl.com',然后使用 expect(window.location.href).toEqual(www.randomurl.com) 进行更新。虽然这确实会通过,但我想避免这种情况,因为我宁愿模拟用户操作而不是将新值注入测试。如果我这样做,即使我删除了我的按钮单击(这实际上会触发函数调用),期望仍然会通过,因为无论如何我已经在我的测试中手动更新了 window.location.href
我选择将 goToThisPage 函数(它将重定向用户)放置在我的功能组件之外。然后我在我的测试文件中模拟 goToThisPage 并在我的测试用例中检查它是否已被调用。我确实知道 goToThisPage 正在被触发,因为我包含了一个 console.log 并且当我运行我的测试时,我在我的终端中看到了它。尽管如此,测试仍然失败。我一直在玩 spyOn 和 jest.doMock/mock 都没有运气
component.js
import React from 'react'
import { ChildComponent } from './childcomponent';
export const goToThisPage = () => {
const url = '/url'
window.location.href = url;
console.log('reached');
};
export const Component = () => {
return (<ChildComponent goToThisPage={ goToThisPage }/>)
}
export default Component;
测试文件:
import * as Component from './component'
import userEvent from '@testing-library/user-event';
jest.doMock('./component', () => ({
goToThisPage: jest.fn(),
}));
describe('goToThisPage', () => {
test('should call goToThisPage when button is clicked', async () => {
const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
const { container, getByTestId } = render(<Component.Component />);
userEvent.click(screen.getByTestId('goToThisPage')); // this is successfully triggered (test id exists in child component)
expect(goToThisPageSpy).toHaveBeenCalled();
// expect(Component.goToThisPage()).toHaveBeenCalled(); this will fail and say that the value must be a spy or mock so I opted for using spy above
});
});
注意:当我尝试只做 jest.mock 时,我收到了这个错误Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
当使用jest.doMock 进行测试时,错误消失了,但实际测试失败了。
如果有人认为此解决方案可以改进,我愿意听取有关解决我的问题的更完善的想法。提前致谢
编辑: 这是我尝试过的另一种方法
import { Component, goToThisPage } from './component'
import userEvent from '@testing-library/user-event';
describe('goToThisPage', () => {
test('should call goToThisPage when button is clicked', async () => {
const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
// I am not certain what I'd put as the first value in the spy. Because `goToThisPage` is an external func of <Component/> & not part of the component
const { container, getByTestId } = render(<Component />);
userEvent.click(screen.getByTestId('goToThisPage'));
expect(goToThisPageSpy).toHaveBeenCalled();
});
});
【问题讨论】:
标签: reactjs unit-testing jestjs react-testing-library window.location