我有一个简单的代码已经编写要测试。
这是我的App.js:
const App: () => React$Node = () => {
function sum(a, b) {
alert(a + b);
return a + b;
}
return (
<>
<Button
title="Sum"
onPress={() => {sum(1,2)}}
/>
);
这是我在__tests__
文件夹中的App-test.js:
import 'react-native';
const sum = require('../App');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
运行npm test
时出现此错误TypeError: sum is not a function
。谁能帮忙。
注意:当我在Android手机上运行它时,它可以正常工作,并且在警告框中显示3。
答案 0 :(得分:1)
这是因为您正在从sum
文件中导入App
,但是它并不是您编写该文件的方法。
您可以执行以下操作:
export const sum = (a, b) => {
alert(a + b);
return a + b;
}
export const App = () => (
<Button
title="Sum"
onPress={() => {sum(1,2)}}
/>
);
并在测试文件中像这样使用它:
import { sum } from '../App'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
它与React Native并没有特别的联系,因为您只是在尝试测试可以在任何框架中使用的特定方法。