最近,我升级了okta-react库,并已将应用程序转换为使用新的挂钩。我现在正在更新测试。 useOktaAuth()
是undefined
。我希望能够模拟它,以便可以测试用户何时登录。
const { authState, authService } = useOktaAuth();
// TypeError: Cannot destructure property `authState` of 'undefined' or 'null'
为了解决这个问题,我尝试通过以下方法模拟该钩子:
jest.mock('@okta/okta-react', () => ({
useOktaAuth: () => {
return {
authState: {},
authService: {}
};
}
}));
那是行不通的。我仍然对如何测试这些组件有任何想法?
谢谢
答案 0 :(得分:1)
我有几乎相同的信息说
TypeError:无法解构'(0,_oktaReact.useOktaAuth)(...)'的属性'authState',因为它是未定义的。**“
组件部分:
import { useOktaAuth } from "@okta/okta-react";
const Login = () => {
const { authState } = useOktaAuth();
...
测试:
jest.mock('@okta/okta-react', () => ({
useOktaAuth: () => {
return {
authState: {},
authService: {}
};
}
}));
describe("<Login /> component tests", () => {
it("Should render Login component", done => {
const wrapper = shallow(<Login/>);
setImmediate(() => {
wrapper.update();
try {
// Your assertion here
done();
} catch (error) {
done.fail(error);
}
});
});
});
答案 1 :(得分:1)
除了Elmatsidis Paul的回答,我还必须添加1个模拟来覆盖useOktaAuth和withOktaAuth:
jest.mock('@okta/okta-react', () => ({
useOktaAuth: () => {
return {
authState: {},
authService: {}
};
},
withOktaAuth: (x: any) => x
}));
答案 2 :(得分:1)
经过不断的研究和工作,这对我有用。
jest.mock("@okta/okta-react/dist/OktaContext", () => ({
useOktaAuth: () => {
return {
authState: {},
authService: {},
};
},
}));
describe("Login", () => {
test("should ", () => {
const wrapper = shallow(<Login authService={null} />);
expect(wrapper.length).toBe(1);
});
});
注意:我将 authService 参数传递给组件。
答案 3 :(得分:0)
jest.mock('@okta/okta-react', () => ({
useOktaAuth: () => {
return {
authState: {},
authService: {}
};
}
}));
test('should render CreateDeploymentManifestPage and ShowDeploymentManifest',
() => {
const myMock= jest.fn();
const wrapper = shallow(<CreateDeploymentManifestPage />);
const basicInfo = wrapper.find(DeploymentBasicInfo);
expect(wrapper.containsAllMatchingElements([
<DeploymentBasicInfo />,
])).toBe(true);
});
答案 4 :(得分:0)
您已经接近:
jest.mock('@okta/okta-react', () => ({
useOktaAuth: () => ({
authState: { isAuthenticated: true},
authService: { handleAuthentication: jest.fn() }
})
}));