I'm trying to test a React app with Rails backend.
(我正在尝试使用Rails后端测试React应用。)
I'm trying to write tests in jest.(我正在开玩笑地编写测试。)
I'm using jest-fetch-mock
node module to mock API calls.
(我正在使用jest-fetch-mock
节点模块来模拟API调用。)
For some reason, it doesn't work properly.(由于某种原因,它无法正常工作。)
This works, but fails in tests(这有效,但测试失败)
//PhoneCodeList.jsx
class PhoneCodeList extends React.Component {
async componentDidMount() {
try {
const response = await fetch(`/api/v1/phone-codes`);
const response_json = await response.json()
// do stuff
console.log(response_json)
}
catch(e) {
console.log(e)
}
}
}
// PhoneCodeList.test.js
import React from 'react'
import {mount, shallow, render, configure} from 'enzyme'
import PhoneCodeList from 'components/PhoneCodeList.js'
import Adapter from 'enzyme-adapter-react-16';
global.fetch = require('jest-fetch-mock')
configure({ adapter: new Adapter() })
const wrapper = mount(<PhoneCodeList />);
describe('Phone list', function() {
test('Lists at least one phone code from database', async () => {
fetch.mockResponse(JSON.stringify({ data: [{id: 1, attributes: { prefix: 'foo'}},
{id: 2, attributes: { prefix: 'bar'}}]}))
var resp = render(<PhoneCodeList />);
expect(resp.find('.phone-code-row').length).toBeGreaterThan(0);
})
})
Response:
(响应:)
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: '', disturbed: false, error: null },
[Symbol(Response internals)]:
{ url: undefined,
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] {} } } }
But mock suddenly starts working if I place it in react file(但是如果我将它放在react文件中,模拟程序突然开始工作)
//PhoneCodeList.jsx
class PhoneCodeList extends React.Component {
async componentDidMount() {
try {
fetch.mockResponse(JSON.stringify({ data: [{id: 1, attributes: { prefix: 'foo'}},
{id: 2, attributes: { prefix: 'bar'}}]}))
const response = await fetch(`/api/v1/phone-codes`);
const response_json = await response.json()
// do stuff
console.log(response_json)
}
catch(e) {
console.log(e)
}
}
}
Obviously, I don't want to leave mocks in my actual React files.
(显然,我不想在我的实际React文件中留下模拟。)
What causes them to fail and how to prevent it?(是什么导致他们失败以及如何防止失败?)
ask by Steve Redka translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…