![](/img/trans.png)
[英]Testing asynchronous componentDidMount that changes state with Jest and Enzyme
[英]Testing a function using jest enzyme - no props/no state
我正在嘗試測試一個函數。 它不會調用任何道具或設置狀態,所以我不確定如何測試它以下是功能 :
sanitizeEmail = (email) => {
let result = email;
if(result.indexOf('@') !== -1 && result.substring(0,result.indexOf('@')).length > 3 ) {
let end = result.indexOf('@');
let temp = '';
for(let i in result.substring(4,end)) {
temp = temp + '*';
}
result = result.substring(0,3) + temp + result.substring(end, result.length);
}
return result
}
測試 :
beforeEach(() => wrapper = mount(<MemoryRouter keyLength={0}><ProfileMenuComponent {...baseProps} /></MemoryRouter>));
測試方法/功能
以下是我通常調用函數或方法來測試的方法:
expect(wrapper.find('ProfileMenuComponent').instance().sanitizeEmail('test')).toEqual();
只需使用不同的參數集調用方法(以便它涵蓋所有流程)。 並比較返回值。
一個例子
方法
export const sortByField = (field, isRevered = false, primerFn) => {
if (field) {
var key = primerFn ? (x) => primerFn(x[field]) : (x) => x[field];
isRevered = !isRevered ? 1 : -1;
return (a, b) => {
/*eslint-disable */
return a = key(a), b = key(b), isRevered * ((a > b) - (b > a));
/*eslint-enable */
}
}
else {
return (a, b) => {
return isRevered ? a < b : a > b;
}
}
}
測試
describe('testing sortByField', () => {
let arrayOfObject = [];
beforeAll(() => {
arrayOfObject = [
{ name: "Name 1", class: "CLASS 4" },
{ name: "Name 2", class: "Class 3" },
{ name: "Name 3", class: "Class 2" },
{ name: "Name 4", class: "Class 1" },
]
})
it('should sort the json array with specified field in ascending order with class as parameter', () => {
expect(arrayOfObject.sort(sortByField("class"))[0].name).toBe("Name 1");
})
it('should sort the json array with specified field in descending order with class and true as parameters', () => {
expect(arrayOfObject.sort(sortByField("class", true))[0].name).toBe("Name 2");
})
it('should sort the json array with specified field in ascending order with class, false and a primerFunction as parameter', () => {
let tPrimerFn = (x) => x.toLowerCase();
expect(arrayOfObject.sort(sortByField("class", false, tPrimerFn))[0].name).toBe("Name 4");
})
it('should sort the simple array in ascending order without passing any field', () => {
expect([4, 3, 2, 1].sort(sortByField())[0]).toBe(1);
})
it('should sort the simple array in ascending order without passing any field', () => {
expect([4, 3, 2, 1].sort(sortByField(null, true))[0]).toBe(4);
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.