问题描述
public function seed()
{
try {
Artisan::call('db:seed',['--force' => true]);
} catch (\Throwable $th) {
return $this->response(
"Failed to seed tables. ".$th->getMessage(),'error'
);
}
return $this->response(
"Successfully migrated and seeded tables.",'success'
);
}
class AuthStore {
token = null
// ...token gets set at some point in time in a function
}
export default new AuthStore() // export singleton
现在我想编写一个测试以确保在调用此函数时使用令牌:
我尝试使用 Jest documentation 中描述的 ES6-Class 模拟来执行此操作,但令牌始终为 import { AuthStore } from '../stores'
export function createFetchHeaders() {
return {
Accept: 'application/json','Content-Type': 'application/json',Authorization: `Bearer ${AuthStore.token}`,}
}
:
undefined
我哪里出错了?据我了解,上述笑话文档以及 this post 这种模拟实现的方式应该会影响测试的功能?!
解决方法
这是因为您导出的是对象而不是类。所以嘲笑不起作用。您可以使用 javascript 手动覆盖函数、对象和类的功能(由 jest 内部使用)。测试代码看起来像这样
var products = [
{
text: 'prod1',value: 1
},{
text: 'prod2',value: 2
},{
text: 'prod3',value: 3
}
];
const newProducts = products.map(({text: label,value})=>({value,label}));
console.log(newProducts );
console.log("===================Another Method====================")
products.map((el)=>{
el.label = el.text
delete el.text
})
console.log(products);
或者在模拟自身时,您可以返回对象而不是函数
import AuthStore from "../../stores/AuthStore"
import {createFetchHeaders} from './';
const mockToken = 'foobar'
describe('createFetchHeaders()',() => {
it('sets Bearer Authorization header using the provided token',() => {
AuthStore.token = mockToken;
const headers = createFetchHeaders()
const expected = `Bearer ${mockToken}`
expect(headers['Authorization']).toEqual(expected)
})
})
而且在createFetchHeaders里面import是错误的,需要这样的
import {createFetchHeaders} from './';
const mockToken = 'foobar'
jest.mock('../../stores/AuthStore',() => {
return { token: 'foobar' }
})
describe('createFetchHeaders()',() => {
const headers = createFetchHeaders()
const expected = `Bearer ${mockToken}`
expect(headers['Authorization']).toEqual(expected)
})
})
您不需要“{}”,因为您默认导出 AuthStore。