Cypress expect vs. Jest expect
(這標題好像什麼決鬥大賽)
問題描述
在 React 專案中,使用 Jest 做 Unit Test、Cypress 做 E2E。 由於兩者都有 "expect" assertion method,使得 Typescript 似乎無法準確推斷 expect 的型別。 導致在 Test file 中:
describe('test Component', () => {
it('should render correctly', () => {
const { container } = render(<Component />);
expect(container).toMatchSnapshot(); // 會報說 expect 沒有 toMatchSnapshot 的 method
});
});
原因
應該是某些特定的 Jest 版本,才會有這個錯誤,可以先參考這篇。
解決方式
在所有 unit test file 加上 declare
declare const expect: jest.Expect;
describe('test Component', () => {
it('should render correctly', () => {
const { container } = render(<Component />);
expect(container).toMatchSnapshot();
});
});
試圖在 Global file 直接做掉這件事,但目前還沒有成功,歡迎分享更好的方法