英文:
How to access local html in cypress out of the react src folder?
问题
我有一个应用程序,其中包含 Cypress 可视化测试。我在该文件夹中创建了一个本地 HTML 文件,尝试将其呈现到 Cypress 代码中。但目标位置始终在 HTML 位置前添加本地基本 URL 的前缀。那么,我该如何访问该文件?
it('visits local file', () => {
cy.visit('chat.html')
cy.contains('local file')
})
我的文件夹结构如下:
app
- src
- test
- index.html
- cypress.test.ts
我的测试位于 test 文件夹中,它是一个 React 应用程序。
英文:
I have an application where I have cypress visual test. I have created a local HTML file in that folder and try to rendering it to the cypress code. But the target location always adding prefix of the local base URL to the HTML location. So how can I access that file?
<!-- language: js -->
it('visits local file', () => {
cy.visit('chat.html')
cy.contains('local file')
})
The folder structure I have...
app
- src
- test
- index.html
- cypress.test.ts
My test is in the test folder and it's a react app.
答案1
得分: 3
你可以使用 cy.mount()
命令,类似于组件测试,但在端对端测试中使用。
这样就完全与 baseUrl
分离了。
Cypress.Commands.add('mount', (html) => {
const testEl = Cypress.$(html)
cy.$$('body').append(testEl)
})
it('访问本地文件', () => {
cy.readFile('./src/chat.html').then(chat => {
cy.mount(chat)
})
cy.contains('本地文件')
})
这对于纯HTML是有效的,例如
// chat.html
<div>本地文件</div>
但由于你有一个React应用,有可能需要将它与React一起挂载。
在这种情况下,完整的组件测试可能更好。
参考链接:React组件测试
英文:
You can use a cy.mount()
command, similar to Component testing but in an e2e test.
That way it's completely separate to baseUrl
.
Cypress.Commands.add('mount', (html) => {
const testEl = Cypress.$(html)
cy.$$('body').append(testEl)
})
it('visits local file', () => {
cy.readFile('./src/chat.html').then(chat => {
cy.mount(chat)
})
cy.contains('local file')
})
This passes for plain HTML, for example
// chat.html
<div>local file</div>
but since you have a React app chances are it will need mounting along with React itself.
In this case, the full Component test would be better.
For reference: React Component Testing
答案2
得分: 1
If you have a baseUrl
set in your cypress config, Cypress will prepend any cy.visit()
that has a relative URL with that value. So, if my baseUrl
is http://localhost:8080
, using cy.visit('chat.html')
will attempt to visit http://localhost:8000/chat.html
.
To avoid this, you will have to clear the baseUrl.
英文:
If you have a baseUrl
set in your cypress config, Cypress will prepend any cy.visit()
that has a relative URL with that value. So, if my baseUrl
is http://localhost:8080
, using cy.visit('chat.html')
will attempt to visit http://localhost:8000chat.html
.
To avoid this, you will have to clear the baseUrl.
it('visits local file', { baseUrl: null }, () => {
cy.visit('./chat.html')
cy.contains('local file')
})
Note: the above will clear the baseUrl only in that specific test. You can apply the same override in describe()
and context()
blocks as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论