我对测试javascript有点新意,我想知道测试生成唯一ID的内容的最佳方法是什么。
编辑:
我真的不想测试我想要的ID,以确保在调用createQuestion函数时该操作返回正确的结果。但测试将失败,因为ID将永远不会匹配,因为它是在函数中生成的。
我目前的代码是这样的。
//------- Action Creator --------//
export const createQuestion = function (inputType) {
const hasOptions = /radio/g.test(inputType);
return {
type: types.CREATE_QUESTION,
question: {
id: uuid.v1(),
priority: null,
title: null,
tip: null,
required: false,
isSaved: false,
hasOptions: hasOptions,
input: {
type: inputType,
options: []
}
}
};
};
//------- TESTS --------//
test('Question Actions', nest => {
nest.test('Create Question', function (assert) {
const msg = 'Questions was Created';
const question = {
id: 1,
priority: null,
title: null,
tip: null,
required: false,
isSaved: false,
hasOptions: false,
input: {
type: 'text',
options: []
}
};
const expectedAction = {
type: types.CREATE_QUESTION,
question
};
const actualAction = actions.createQuestion('text');
assert.deepEqual(actualAction, expectedAction, msg);
assert.end();
});

由于在动作创建器中生成唯一ID,因此除非我在函数返回动作后更改ID,否则无法进行模拟。
有这样的东西
const changeUUID = obj => {
const newobj = {...obj};
newobj.question.id = 1;
return newobj;
};
答案 0 :(得分:1)
除非您对ID具有特定值感兴趣,否则将其从expectedAction
中排除是完全正常的。
assert.ok(actualAction.question.id);
delete actualAction.question.id;
assert.deepEqual(actualAction, expectedAction, msg);