index.js的唯一目的是运行foo
和bar
函数:
//index.js
import foo from './foo.js'
import bar from './bar.js'
foo()
bar()
如何在运行index.js时测试foo
和bar
被执行?
答案 0 :(得分:0)
这里的文档非常直接.. https://facebook.github.io/jest/docs/en/mock-functions.html
__测试__ / index.js
<09:56:44 IST 07/03/2018> <Error> <HTTP> <BEA-101107> <[ServletContext@1357305147[app:Mobile-V1.0.0-EAR module:Mobile-V1.0.0-EAR path:/Mobile spec-version:2.5]] Problem occurred while serving the error page.
java.lang.NullPointerException
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:92)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.web.method.HandlerMethod.createWithResolvedBean(HandlerMethod.java:219)
Truncated. see log file for complete stacktrace
>
checkUser start date:Wed Mar 07 09:56:44 IST 2018
LOGINURL=http://localhost:8000
client.target http://localhost:8000/Entitlement/api/login/customers
customerId=139
source :login/customers/139/entitlements
javax.servlet.ServletException: javax.ws.rs.ProcessingException: Error closing message content input stream.
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:419)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
运行它
jest.mock("../foo");
jest.mock("../bar");
const foo = require("../foo");
const bar = require("../bar");
test("functions are called", done => {
require("../index");
expect(foo.mock.calls.length).toBe(1);
expect(bar.mock.calls.length).toBe(1);
done();
});
文件结构 - 对于需求路径没有什么特别之处,如果它找不到文件那么你的路径就错了..
$ yarn test
yarn run v1.5.1
$ jest
PASS __tests__/index.js
✓ functions are called (14ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.955s
Ran all test suites.
✨ Done in 1.51s.
答案 1 :(得分:0)
首先,我将集中精力测试foo
和bar
函数,确保他们做他们必须做的事情。
例如,如果函数foo为()=>{ return 'foo() is working' }
,我创建一个名为foo.test.js
的文件,并为其编写2-3个测试。
test('make sure it returns something', () => {
expect(!foo()).toBe(false);
});
test('make sure it returns string', () => {
var val = foo();
expect(typeof val === 'string').toBe(true);
});
test('make sure it returns string', () => {
expect(foo()==='foo() is working').toBe(true);
});
这将确保我的foo.js
正在执行它所假设的操作然后我创建另一个名为index.text.js的文件,并在其中我将进行模拟测试
jest.mock("../foo");
const foo = require("../foo");
test('make sure foo is called', () => {
expect(foo).toBeCalled();
});
test('make sure foo run only once', () => {
expect(foo.mock.calls.length).toBe(1);
});
现在假设您已经安装了jest并且正确配置了package.json,您可以简单地运行:npm run test或者如果您有纱线,您可以运行纱线测试......