我有一个小的实用程序功能,我正在React-TS项目上对Jest和Enzyme进行了一些测试。在该项目的JS文件中,出现以下错误:
"validateUsername" is read-only.
这是实用程序本身:
export const validateUsername = value =>
listUsers()
.then(({ data }) => {
if (Array.isArray(data) && data.find(userData => userData.username === value)) {
throw 'Username already exists';
}
})
.catch(error => {
throw serverErrorResponseUtil(error);
});
这是它的测试:
describe('Validate Username', () => {
const validateUsernameFn = jest.fn();
beforeEach(() => {
validateUsername = validateUsernameFn;
});
it('Should throw an error if the given value exists', async () => {
try {
await validateUsername('username');
} catch (e) {
expect(e).toEqual('Username already exists');
}
});
it('Accept the data if the passed userName is unique', async () => {
expect(() => validateUsername('Username is unique')).not.toThrow();
});
});
我在这里收到错误:validateUsername = validateUsernameFn;
。事情是这个文件是一个js。为什么我会收到有关只读的TS错误。你们可以帮我吗?
答案 0 :(得分:1)
您可能已经找到了解决方案,但问题是先导入validateUsername
,然后在beforeEach()
中重新定义它。
我不知道为什么您需要beforeEach()
中的代码,但是如果您想访问初始的validateUsername
并且享受模拟的好处,我建议您使用jest.spyOn
。 / p>
在beforeEach()
中,您可以根据需要清除测试之间的模拟。
答案 1 :(得分:0)
好像您要将函数导出为export const validateUsername
,然后尝试在引发错误的行上重新分配它。 constant
不能重新分配(通过设计),只有let
和var
可以重新分配。
尚不完全清楚,但是您似乎不需要在这里使用jest.fn
-这是用于创建模拟“间谍”函数,因此您可以例如检查是否使用正确的参数调用了函数。您正在尝试测试函数本身,因此无需将其重新分配给一个玩笑的间谍。