在Next.js+Cypress环境中使用Nock JS遇instanceof错误求助
问题解决:Cypress测试中使用Nock出现
Right-hand side of 'instanceof' is not an object错误 错误原因
Nock是Node.js专属的HTTP拦截库,你的Cypress测试运行在浏览器环境,直接引入Nock会因为缺少Node.js特定模块(比如http)导致环境不兼容,触发该错误。另外,你的Next.js应用通过getServerSideProps在服务器端发起API请求,Nock无法跨进程拦截服务器端的请求,本来就达不到模拟API的目的。
解决方案:改用Cypress内置的cy.intercept()
Cypress的cy.intercept()可以拦截所有经过其代理的HTTP请求,包括Next.js服务器端发起的请求,完全适配SSR场景。修改后的测试代码如下:
describe('weather app spec', () => { it('can load the current weather', () => { // 拦截OpenWeatherMap的API请求并返回模拟数据 cy.intercept('GET', 'https://api.openweathermap.org/data/2.5/weather', { "coord": { "lon": -73.9629, "lat": 40.6884 }, "weather": [ {"id": 211, "main": "scattered clouds", "description": "scattered clouds", "icon": "11d"}, {"id": 500, "main": "Rain", "description": "scattered clouds", "icon": "10d"} ], "base": "stations", "main": { "temp": 299.25, "feels_like": 299.25, "temp_min": 296.15, "temp_max": 303.46, "pressure": 1014, "humidity": 75 }, "cod": 200 // 必须添加该字段,与getServerSideProps的判断逻辑匹配 }).as('getWeather'); cy.visit('/') cy.get('#__next').should('contain', "Click to get your weather") cy.contains('Get Weather').click() // 等待API请求完成后再断言 cy.wait('@getWeather'); cy.contains("Current weather is scattered clouds") }) })
关键优化说明
- 添加
cod字段:你的getServerSideProps通过Number(result.cod) === 200判断请求成功,模拟数据必须包含该字段,否则会返回forecastSuccess: false,导致断言失败。 - 使用
cy.wait():确保API请求完成后再执行断言,避免异步请求未完成时的断言失效。
内容的提问来源于stack exchange,提问作者Jason FB
相关产品推荐
相关产品推荐

