我有一个在window
中定义的方法,然后在我的react组件中使用。
如何正确模拟方法,因为我在测试Cannot read property 'textContent' of null
窗口方法
import * as htmlEncoder from 'node-html-encoder'
window.identityServer = (function () {
const encoder = htmlEncoder.Encoder()
const identityServer = {
getModel () {
const modelJson = document.getElementById('modelJson')
const encodedJson = typeof modelJson.textContent !== undefined ? modelJson.textContent : modelJson.innerHTML
const model = JSON.parse(encoder.htmlDecode(encodedJson))
return model
},
}
return identityServer
})()
export const identityServerModel = window.identityServer.getModel()
登录组件:
const {loginUrl, antiForgery, errorMessage, rememberMe} = identityServerModel
export class Login extends Component {
render() {
const {classes} = this.props
return (
<div style={layout.flexColumn}>
{loginUrl, antiForgery, errorMessage, rememberMe}
</div>
)
}
测试
import {Login} from '../../../src/components/loginPage/login'
import {TextField, Checkbox} from '@televic/react-components'
// import {identityServerModel} from '../../../src/components/loginPage/identityServerModel'
describe.only('<Login />', () => {
let loginPage
beforeEach(() => {
// sinon.stub(window, 'identityServer')
loginPage = <Login classes={{}} />
})
it('should call handleChange when clicking to <Checkbox/>', () => {
let checkbox = loginPage.find(Checkbox).props()
})
})